【问题标题】:How do I use a regex in JavaScript to extract specific parts of a URL path?如何在 JavaScript 中使用正则表达式来提取 URL 路径的特定部分?
【发布时间】:2021-02-02 16:20:02
【问题描述】:

现在,我正在尝试采用这种格式的 URL:

https://www.example.com/{section}/posts/{number}

并获取部分和编号。我需要用正则表达式来做;我不能把它分解成一个零件数组。我试过了:

var sect = myURL.match('https://www.example.com/[^/]+');

但我得到了输出"https://www.example.com/{section}"。我希望能够获得sectionnumber。如何在 JavaScript 中执行此操作?

【问题讨论】:

  • 我不断收到Uncaught SyntaxError: Unexpected token '^'
  • 抱歉打错了,应该是myURL.match(/^https?:\/\/www\.example\.com\/([^\/]+)\/posts\/(\d+)\/?$/) 并抓取2个捕获组`
  • 谢谢!有没有办法分别提取sectionnumber
  • @user11039951 你为什么要分开,它在捕获组中......
  • 它将从结果数组中单独提取为matches[1]matches[2]

标签: javascript regex


【解决方案1】:

您可以将matches 的输出分配给多个变量,如下所示:

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
  • \/?$:在结束前匹配可选的尾随 /

【讨论】:

  • 反斜杠到底有什么作用?逃跑?
  • 是的,这是为了转义特殊的正则表达式元字符,我们必须在 Javascript 正则表达式中转义 /
  • const [sec, num] = myURL.match(/* ... */).slice(1);
  • 是的@PeterSeliger 和slice 也可以丢弃数组的第一个元素
【解决方案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']);

【讨论】:

  • 我需要用正则表达式来做
  • @user11039951 为什么?
  • 因为我只是这样做
  • @user11039951 哦,好吧,.split() 接受正则表达式文字而不是字符串,所以我更新了我的答案以使用实际的正则表达式。
【解决方案3】:

当然需要从URLpathname 中检索这种路径信息,例如named capturing groups 对应写成的RegExp

对于提供的示例,URL 的路径名将是 ...

/FOOBARBAZ/posts/987

..,因此使用命名捕获组的正则表达式确实看起来像 ...

/\/(?<section>[^\/]+)\/posts\/(?<number>[^\/?#]+)/

... 读起来像 ...

  • \/(?&lt;section&gt;[^\/]+) ... 匹配单个斜线,然后捕获任何不等于斜线的字符序列,并将此捕获组命名为 section ... 然后 ...
  • \/posts ... 匹配单个斜杠和序列 posts ... 然后 ...
  • \/(?&lt;number&gt;[^\/?#]+) ... 匹配单个斜线,然后捕获任何不等于斜线、问号和哈希的字符序列,并将此捕获组命名为 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; }

【讨论】:

  • @user11039951 ...对该方法有任何疑问吗?
猜你喜欢
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
相关资源
最近更新 更多