我有这个网址:
http://example.com/things/stuff/532453?morethings&stuff=things&ver=1
我在那里需要那个数字。我得到的最近的是
(\ d *)?\?
但这包括问号。基本上所有前面的数字?一直到斜线所以输出是532453。
答案 0 :(得分:3)
尝试以下正则表达式(?!\/)\d+(?=\?)
:
url = "http://example.com/things/stuff/532453?morethings&stuff=things"
url.match(/(?!\/)\d+(?=\?)/) # outputs 532453
此正则表达式将尝试仅在/
之后和?
之前使用negative/positive lookahead匹配任何一系列数字而不返回/
或?
为比赛的一部分。
开发人员工具中的快速测试:
# 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
答案 1 :(得分:0)
试试这个:
url = "http://example.com/things/stuff/532453?morethings&stuff=things"
number = url.match(/(\d+)\?/g)[0].slice(0,-1)
虽然这种做法有点天真,但它确实有效。它抓住数字?最后,使用?
从结尾删除slice
。
答案 2 :(得分:0)