【问题标题】:How do I extract only part of a matched string with regex? [duplicate]如何使用正则表达式仅提取匹配字符串的一部分? [复制]
【发布时间】:2018-06-21 00:11:46
【问题描述】:
'https://twitter.com/pixelhenk/status/891303699204714496'.match(/\/status\/(\d+)/g)

给我

[ "/status/891303699204714496" ]

我如何只得到号码?我以为把它放在括号里是这样做的,但显然不是。

【问题讨论】:

  • 改用exec()
  • 号码在第一个捕获组中。
  • @ctwheels:我们可以标记多个。 :-)
  • 必须是正则表达式吗? const num = 'https://twitter.com/pixelhenk/status/891303699204714496'.split("/").pop();

标签: javascript regex


【解决方案1】:

是的,捕获组会执行此操作。您在数组中看不到它,因为您使用了 String#matchg 标志。删除g 标志(并从数组中取出第二个条目,即第一个捕获组):

console.log('https://twitter.com/pixelhenk/status/891303699204714496'.match(/\/status\/(\d+)/)[1]);

...或使用RegExp#exec 代替String#match

console.log(/\/status\/(\d+)/g.exec('https://twitter.com/pixelhenk/status/891303699204714496')[1]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多