繁体   English   中英

如何在 Javascript 中使用正则表达式来提取 URL 路径的特定部分

[英]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}"我希望能够获得sectionnumber 如何在 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命名捕获组URLpathname中检索这种路径信息。

对于提供的示例,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM