我有这种URL,我想使用RegEx进行匹配。
第一个123
始终是数字,而第二个123a_12a3
是字母数字并且可以带有下划线。
我想创建一个正则表达式,以检查它是否与上述两个URL相匹配。
我创建了以下代码:
let result = new RegExp('\\binvoices/download\\b').test(url);
那行得通,但我认为有一种更好的方法可以匹配这两个URL,也许可以检查这两个参数是否存在,因为现在仅匹配1。
我是Regex的新手,非常感谢您的帮助!
谢谢。
答案 0 :(得分:1)
类似这样的东西应该与这些URL中的一个相匹配
const rx = /\/sample\/company\/\d+\/invoices\/(download|view)\/\w+$/
const urls = [
"http://example.com/sample/company/123/invoices/download/123a_1a23",
"http://example.com/sample/company/123/invoices/view/123a_12a3",
"http://example.com/sample/other/123/invoices/view/123a_12a3",
"http://example.com/sample/company/123/invoices/upload/123a_12a3",
]
urls.forEach(url => console.log(url.slice(18), rx.test(url)))
打破现状...
\/sample\/company\/ - literal "/sample/company/"
\d+ - one or more numbers
\/invoices\/ - literal "/invoices/"
(download|view) - "download" or "view"
\/ - a literal "/"
\w+ - one or more "word" characters, ie alpha-numeric or underscore
$ - the end of the string
答案 1 :(得分:1)
尝试:
var result = new RegExp('invoices\/(download|view)\/', "i").test(url);
带管道的(和)括号使您可以检查两件事。