【问题标题】:How to split regex matches如何拆分正则表达式匹配
【发布时间】:2019-09-20 15:52:09
【问题描述】:

我想在一个字符串中匹配所有给定的(),但我遇到了麻烦,因为我当前的解决方案匹配(),而我的意图是得到像['(',')'] 这样的拆分结果

我的regex 表达式是:/[()]+/gRegex101 playground

我怎样才能设法仅使用正则表达式表达式获得所需的行为?

const matchType = str => str.match(/[()]+/g)

console.log(matchType('{(})[]')); // ['(',')]

// Expected ['(',')']
console.log(matchType('{[()]}')); // ['()']

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    不要使用量词+

    当你使用+ 量词+ 表示一个或多个时间,

    [()]+ 这意味着匹配( or ) 一次或多次,因此当您有类似() 的字符串时,它会将其视为一次匹配

    const matchType = str => str.match(/[()]/g)
    
    console.log(matchType('{(})[]')); // ['(',')]
    
    // Expected ['(',')']
    console.log(matchType('{[()]}'));

    【讨论】:

      【解决方案2】:

      你只需要摆脱+

      const matchType = str => str.match(/[()]/g)
      

      + 表示您将匹配一个或多个括号。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 2012-02-09
        相关资源
        最近更新 更多