我有这个网址:
http://example.com/things/stuff/532453?morethings&stuff=things&ver=1
我只需要中间的那个数字。最接近的匹配是 (\d*)?\? ,但这包括了问号。基本上,所有在问号之前直到斜杠的数字都会被匹配,因此输出为 532453。我有这个网址:
http://example.com/things/stuff/532453?morethings&stuff=things&ver=1
我只需要中间的那个数字。最接近的匹配是 (\d*)?\? ,但这包括了问号。基本上,所有在问号之前直到斜杠的数字都会被匹配,因此输出为 532453。尝试以下正则表达式(?!\/)\d+(?=\?)
:
url = "http://example.com/things/stuff/532453?morethings&stuff=things"
url.match(/(?!\/)\d+(?=\?)/) # outputs 532453
/
和?
之间的任何一系列数字,使用负/正向先行断言,但不会将/
或?
作为匹配的一部分返回。在开发者工具中进行快速测试:# create a list of example urls to test against (only one should match regex)
urls = ["http://example.com/things/stuff/532453?morethings&stuff=things",
"http://example.com/things/stuff?morethings&stuff=things",
"http://example.com/things/stuff/123a?morethings&stuff=things"]
urls.forEach(function(value) {
console.log(value.match(/(?!\/)\d+(?=\?)/));
})
# returns the following:
["532453"]
null
null
试试这个:
url = "http://example.com/things/stuff/532453?morethings&stuff=things"
number = url.match(/(\d+)\?/g)[0].slice(0,-1)
虽然这种方法有点幼稚,但它确实有效。它会获取以 ? 结尾的数字,然后使用 slice
去掉末尾的 ?
。