首页 > 解决方案 > Javascript 正则表达式匹配 2 个 URL

问题描述

我有这种 URL,我想使用 RegEx 匹配它。

  1. “http://example.com/sample/company/123/invoices/download/123a_1a23
  2. “http://example.com/sample/company/123/invoices/view/123a_12a3”

第一个123总是数字,而第二个123a_12a3是字母数字,可以有下划线。

我想创建一个正则表达式来检查它是否与上面的这 2 个 URL 匹配。

我创建了这段代码:

let result = new RegExp('\\binvoices/download\\b').test(url);

那行得通,但我认为有更好的方法来匹配这 2 个 URL,并可能检查这 2 个参数是否存在,因为现在只匹配 1。

我是 Regex 的新手,非常感谢任何帮助!

谢谢。

标签: javascriptregex

解决方案


像这样的东西应该匹配这些网址中的任何一个

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

推荐阅读