【问题标题】:How to extract specific substring from a string using a one liner如何使用单行从字符串中提取特定子字符串
【发布时间】:2020-06-06 01:19:16
【问题描述】:

输入:parent/123/child/grand-child

预期输出:child

尝试 1:(?<=\/parent\/\d*)(.*)(?=\/.*)

错误:lookbehind 中的量词使其宽度不固定,look behind 不接受 * 但我不知道数字的宽度,因此必须使用它

尝试 2:(有效,但 2 个衬垫):

const currentRoute='/parent/123/child/grand-child'
let extract = currentRoute.replace(/\/parent\/\d*/g, '');
extract = extract.substring(1, extract.lastIndexOf('/'));
console.log('Result', extract)  

如何使用单行获得提取物,最好使用正则表达式

【问题讨论】:

  • 为什么不使用捕获组而不是匹配? console.log("parent/123/child/grand-child".match(/parent\/\d+\/(\w+)\/.*/)[1]);
  • 我知道你说的最好是正则表达式,但.split("/")[2] 也可以
  • @EugenSunic 查看 cmets 中的示例。
  • 您可以在后视中使用量词,但这并未得到广泛支持。例如,它在 Chrome 和 Nodejs 中。
  • 您可以将模式更新为 (?<=parent\/\d*\/)([^\/]+)(?=\/) 并在 Chrome 中查看 regex101.com/r/CA7LNH/1 请注意,可以省略末尾前瞻中的 .*。

标签: javascript regex


【解决方案1】:

您当前的模式将匹配 123/child 而不是 child 仅因为在 \d* 之后缺少正斜杠(注意 * 表示 0 或更多次)

如果存在更多正斜杠,由于.*,它也会过度匹配(参见demo)。


相反,您可以使用捕获组并使用match。

parent\/\d+\/(\w+)\/

Regex demo

该值在捕获组 1 中。

let res = "parent/123/child/grand-child".match(/parent\/\d+\/(\w+)\//);
if (res) console.log(res[1])

可以通过后向模式获取 child 的值

(?<=parent\/\d*\/)([^\/]+)(?=\/)

Regex demo

请注意,这尚未得到广泛支持。

let res = "parent/123/child/grand-child".match(/(?<=parent\/\d*\/)([^\/]+)(?=\/)/);
if (res) console.log(res[0])

【讨论】:

    【解决方案2】:

    怎么样

    currentRoute.match(/\/parent\/(?:.*)\/(.*)\//)[1]
    

    【讨论】:

      【解决方案3】:

      如果格式固定,则使用.split("/")[2]获取第三个元素

      console.log(currentRoute.split("/")[2]);
      

      “孩子”


      要匹配字符串的 parent 部分,请使用 .match(/^parent\/[^\/]+\/([^\/]+)/)[1]

      console.log(currentRoute.match(/^parent\/[^\/]+\/([^\/]+)/)[1]);
      

      “孩子”

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2023-03-24
        • 2023-04-03
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 2011-11-17
        • 1970-01-01
        • 2011-01-19
        相关资源
        最近更新 更多