javascript - Javascript 正则表达式匹配 2 个 URL
问题描述
我有这种 URL,我想使用 RegEx 匹配它。
- “http://example.com/sample/company/123/invoices/download/123a_1a23
- “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 的新手,非常感谢任何帮助!
谢谢。
解决方案
像这样的东西应该匹配这些网址中的任何一个
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
推荐阅读
- android - 如何同时(不在 UI 线程上)执行多个视频和图像的压缩(根据我的用例最多 10 个文件)?
- c# - Monogame“找不到 ContentTypeReader 类型”
- vue.js - 键值对的 Vue 插值
- python - 无法在 python 中使用 openpyxl 写入 excel
- python - Pymongo 在子集合中找到?
- r - 一次检查向量和矩阵数据类型
- vue.js - Vue js 无法解析组件中的css代码
- django - 通过电子邮件登录时,AnonymousUser' 对象没有属性 '_meta
- python - 在同一个类的另一个方法中添加方法
- php - 完整性约束违规:1048 列 'cd_id' 在 laravel 中不能为空