正则表达式匹配可选部分
例如,我这里有两个可能的字符串。
/user/name
我
/user/name?redirect=1
试图找出正确的正则表达式来匹配以下结果:
Array ([0] => /user/name [1] => user [2] => name)
我认为我遇到问题的部分是问号和其后的 GET 查询是可选的,并且只会出现其中的一些时间。我尝试了很多不同的方法,但似乎无法想出一个正则表达式来匹配字符串,无论 ?** 是否存在。
So I have two possible strings here for example.
/user/name
and
/user/name?redirect=1
I'm trying to figure out the proper regex to match either with a result of:
Array ([0] => /user/name [1] => user [2] => name)
I think the part I'm having an issue with is that the question mark and the GET query after it are optional and will only be there some of the time. I've tried many different things and can't seem to come up with a regex to match the strings whether the ?** is there or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要使用正则表达式,
使用 parse_url() 和 explode()
Don't use a regex,
Use parse_url(), and explode()
?
是“零或一”量词。因此,您可以将(\?.*)?
附加到正则表达式中,该正则表达式可以选择匹配零个或一个文字问号实例,后跟任意数量的字符。?
is the "zero-or-one" quantifier. So you could append(\?.*)?
to your regex, which will optionally match zero or one instances of a literal question-mark followed by any number of characters.在正则表达式中,您可以使用
?
参数将某些内容指定为可选。例如,正则表达式n?ever
匹配ever
和never
。在您的情况下,您可能需要类似
/([A-Za-z0-9]+)/([A-Za-z0-9]+)(\?redirect=1)?
这将匹配
/.../...
(假设“...”由字母和数字组成)或/.../...?redirect=1
如果问号后面可能有更多可能的标志,而不仅仅是
redirect=1
,请尝试更通用的:/([A-Za-z0-9]+)/ ([A-Za-z0-9]+)(\?[A-Za-z0-9]+=[A-Za-z0-9]+)?(&[A-Za-z0-9] +=[A-Za-z0-9]+)*
In regex you can specify something as optional using the
?
parameter. So for instance, the regexn?ever
matchesever
andnever
.In your case, you might want something like
/([A-Za-z0-9]+)/([A-Za-z0-9]+)(\?redirect=1)?
This will match
/.../...
(given the "..." consist of letters and numbers) or/.../...?redirect=1
If there are more possible flags that could come after the question mark than simply
redirect=1
, try the more general:/([A-Za-z0-9]+)/([A-Za-z0-9]+)(\?[A-Za-z0-9]+=[A-Za-z0-9]+)?(&[A-Za-z0-9]+=[A-Za-z0-9]+)*
这是一个前瞻断言。它不会包含在比赛本身中。
但就像其他答案一样,您不应该使用正则表达式来解析 URL。为了完整性,仅发布特定问题的实际答案。
This is a look ahead assertion. It won't be included in the match itself.
But like the other answers suggest you shouldn't use regex to parse URLs. Just posting the actual answer to the specific question for completeness.