[英]How do I use a regex in Javascript to extract specific parts of a URL path
現在,我正在嘗試采用這種格式的 URL:
https://www.example.com/{section}/posts/{number}
並獲取部分和編號。 我需要用正則表達式來做; 我不能把它分解成一個零件數組。 我努力了:
var sect = myURL.match('https://www.example.com/[^/]+');
但我得到了 output "https://www.example.com/{section}"
我希望能夠獲得section
和number
。 如何在 Javascript 中執行此操作?
您可以將matches
的 output 分配給多個變量,如下所示:
var myURL = 'https://www.example.com/mysection/posts/1234'; [$0, sec, num] = myURL.match(/^https?:\/\/www\.example\.com\/([^\/]+)\/posts\/(\d+)\/?$/); console.log(sec) //=> mysection console.log(num) //=> 1234
正則表達式詳細信息:
^
: 開始https?:\/\/www\.example\.com\/
:([^\/]+)
:匹配任何不是/
的字符的 1+ 並捕獲為組 #1\/posts\/
:匹配/posts/
(\d+)
:匹配 1+ 個數字並捕獲為組 #2\/?$
: 在結束之前匹配一個可選的尾隨/
如果您不必驗證字符串實際上是 URL ,那么只需將其拆分為正斜杠即可。
var parts = `https://www.example.com/{section}/posts/{number}`.split(/\//); console.log(parts[3]); console.log(parts[5]);
如果您“必須”使用正則表達式匹配,那么:
var matches = `https://www.example.com/{section}/posts/{number}`.match(/.*\/(?<section>[^\/]+)\/posts\/(?<number>.+)/); console.log(matches.groups['section']); console.log(matches.groups['number']);
原因之一需要通過例如相應編寫的RegExp
的命名捕獲組從URL
的pathname
中檢索這種路徑信息。
對於提供的示例,url 的路徑名將是...
/FOOBARBAZ/posts/987
..,因此使用命名捕獲組的正則表達式確實看起來像...
/\/(?<section>[^\/]+)\/posts\/(?<number>[^\/?#]+)/
...讀起來像...
\/(?<section>[^\/]+)
... 匹配單個斜杠,然后捕獲任何不等於斜杠的字符序列,並將此捕獲組section
命名為 ... 然后...\/posts
posts
匹配單個斜杠和序列 post ... 然后...\/(?<number>[^\/?#]+)
... 匹配單個斜線,然后捕獲不等於斜線、問號和 hash 的任何字符序列,並將此捕獲組命名為number
。 const { section, number } = new URL('https://www.example.com/FOOBARBAZ/posts/987').pathname.match(/\/(?<section>[^\/]+)\/posts\/(?<number>[^\/?#]+)/).groups; console.log({ section, number });
.as-console-wrapper { min-height: 100%;important: top; 0; }
沒有命名組的相同捕獲方法確實看起來像那樣......
const [ section, number ] = new URL('https://www.example.com/FOOBARBAZ/posts/987').pathname.match(/\/([^\/]+)\/posts\/([^\/?#]+)/).slice(1); console.log({ section, number });
.as-console-wrapper { min-height: 100%;important: top; 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.