簡體   English   中英

Javascript 正則表達式匹配 2 個 URL

[英]Javascript Regex to match 2 URLs

我有這種我想使用 RegEx 匹配的 URL。

  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 的新手,非常感謝任何幫助!

謝謝。

像這樣的東西應該匹配這些網址中的任何一個

 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

嘗試:

var result = new RegExp('invoices\/(download|view)\/', "i").test(url);

帶有 pipe 的 ( 和 ) 括號允許您檢查兩件事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM