仅从 URL 获取 URI 段 [英] Get only URI segments from URL
问题描述
我正在尝试使用正则表达式获取 URI 段.
I am trying to get the URI segments using regular expression.
示例 URI:
http://abc.com/hello/hi/bye?humm/ok=hi&ya=yaya/wow/waaah
^^^^^ ^^ ^^^ ^^^ ^^^^^
我正在尝试:
/(?<=\/)[\w-]+(?=(\/|$|\r|\?))/g
但是它不能正常工作.查询字符串没有被排除 (wow/waaah
).
But it's not working properly. The query string is not getting excluded (wow/waaah
).
因此,当我尝试以下操作时,一切都被排除在外:
So, when I tried the following, everything got excluded:
/(?<!?.+)(?<=\/)[\w-]+(?=(\/|$|\r|\?))/g
这有什么问题吗?
推荐答案
您忘记转义第二个正则表达式中的第二个 ?
.它应该是:
You forgot to escape the second ?
in the second regex. It should read:
<代码>/(?
注意:您可以使用像这样的字符类来改进正则表达式:
Note: You could improve the regex by using character classes like so:
/(?<!\?.+)(?<=\/)[\w-]+(?=[/\r\n?]|$)/g
对于满足所有不同风格的正则表达式的最低公分母解决方案,您需要一个两步过程:
For a lowest common denominator solution to cater for all the different flavours of regex, you need a two step process:
- 删除尾随的
?
和所有后续字符(如果存在):^[^/]+//[^/]+([^?]+)
保留捕获组 1 中返回的字符串.
- 通过循环提取 URI 段:
/([\w-]+)
这些段在捕获组 1 中返回.
- Remove the trailing
?
and all following chars (if it exists):
^[^/]+//[^/]+([^?]+)
Keep the string returned in capture group 1.
- Extract the URI segments by looping through:
/([\w-]+)
The segments are returned in capture group 1.
这篇关于仅从 URL 获取 URI 段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!