[英]How to write a regex to extract a number from these URLs?
我正在尝试编写一个正则表达式来匹配这些URL中的数字( 12345678
和1234567890
)。
http://www.example.com/p/12345678
http://www.example.com/p/12345678?foo=bar
http://www.example.com/p/some-text-123/1234567890?foo=bar
规则:
/p/
我的尝试:
\/p\/([0-9]+)
这匹配第一和第二,但不是第三。 所以我尝试过:
\/p\/[^\/?]*\/?([0-9]+)
没有快乐。
正则表达式可能不适合这项工作。 看起来在每种情况下,使用URL解析器拆分URL会更有意义。 从您的示例中可以看出,数字部分始终是URL路径部分中的最后一项。 我不确定您使用的是哪种语言,但是许多语言都提供了可以将URL解析为其组成部分的功能。
$path = parse_url($url, PHP_URL_PATH);
if(strpos($path, "/p/") === 0) {
$base = basename($path);
} else {
// error
}
每次都有效,假设$ url是您正在解析的字符串。
我扩展了你的版本,它现在适用于所有的例子:
\/p\/(.+\/)*(\d+)(\?.+=.+(&.+=.+)*)?$
如果您不关心URL是否有效,则可以将正则表达式缩小为:
\/p\/(.+\/)*(\d+)($|\?)
如果我理解得很好,你想要的数字只能是:
/p/123?foo=bar456
匹配123
和 /p/foobar?foo=bar456
什么都不匹配 然后,您可以使用以下正则表达式:
(?=/p/).*/\K\d+
说明
(?=/p/) # lookahead: check '/p/' is in the URL
.*/ # go to the last '/' thanks to greediness
\K # leave everything we have so far out of the final match
\d+ # select the digits just after the last '/'
为避免转义正斜杠,请不要将它们用作正则表达式分隔符 : #(?=/p/).*/\\K\\d+#
将正常运行。
\/p\/(?:.*\/)?(\d+)\b
你可以尝试这个。这将根据你的密码捕获整数。参见demo.Grab捕获或组。
https://regex101.com/r/dU7oN5/29
$re = "/\\/p\\/(?:.*\\/)?(\\d+)\\b/";
$str = "http://www.example.com/p/12345678\nhttp://www.example.com/p/12345678?foo=bar\nhttp://www.example.com/p/some-text-123/1234567890?foo=bar";
preg_match_all($re, $str, $matches);
var regex = new Regex(@"/(?<ticket>\d+)");
var subject = "http://www.example.com/p/some-text-123/1234567890?foo=bar";
var ticket = regex.Match(subject).Groups["ticket"].Value;
产量:1234567890
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.