我正在尝试使用 Javascript 正则表达式捕获我的域和 .html
(如果存在)之间的任何字符串,但这样做时遇到问题。有什么建议吗?
Regex:
www\.mysite\.com\/(.*)(\.html) // Does not capture 'www.mysite.com/cat'
www\.mysite\.com\/(.*)(\.html)? // Captures the '.html'
Test Data:
www.mysite.com/aadvark.html (capture group should be 'aadvark')
www.mysite.com/bird.html (capture group should be 'bird')
www.mysite.com/cat (capture group should be 'cat')
最佳答案
许多这样的问题可以通过更具体地使用点匹配全部来解决。如果将 .*
更改为 [^.]*
(0+ 个非 .
字符),您将获得预期结果。
/www\.mysite\.com\/([^.]*)(\.html)?/
这是因为当您将 (\.html)
设置为可选时,.*
会贪婪地继续到末尾。这也可以通过使用 ?
来修复,使重复变得“懒惰”(一旦表达式的下一部分匹配就停止);但是,您需要使用 $
来锚定表达式的末尾。
/www\.mysite\.com\/(.*?)(\.html)?$/
<小时/>
我首先推荐这个。但是,第二个通过匹配 www.mysite.com/foo.bar.html
中的 foo.bar
等内容更具包容性。
关于javascript - Regex JS - 创建没有指定单词的捕获模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165506/