正则表达式 - 从URL中提取数字

5
3个回答

7

尝试以下正则表达式(?!\/)\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

@AnthonyForloney 这个lookaround东西真是太棒了。 - vjdhama
@vjdhama 这是一个非常有用的功能,我认为它在提高正则表达式的准确性方面发挥了巨大作用。 - Anthony Forloney

2

这将获取URL中的任何其他数字(请注意末尾的1),我只需要在“/”和“?”之间的数字。 - Matt Coady
1
@MattCoady 你只需要添加负向前瞻 (?!/) 和正向前瞻 (?=?) 来确保你的字符串在 / 和 ? 之间。这样写:(?!/)[\d]+(?=?) - Luc

0

试试这个:

url = "http://example.com/things/stuff/532453?morethings&stuff=things"
number  = url.match(/(\d+)\?/g)[0].slice(0,-1)

虽然这种方法有点幼稚,但它确实有效。它会获取以 ? 结尾的数字,然后使用 slice 去掉末尾的 ?


嗯...我应该给出一个更好的例子。这也会获取URL中的任何其他数字。我已经更新了示例。我只需要在/和?之间的那些数字。 - Matt Coady
如果他的链接在“things”部分包含更多数字,则会导致错误的结果。 - Enissay
我注意到了。尝试使用不同的正则表达式。 - vjdhama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接