【问题标题】:Extending a regex to capture multiple conditions扩展正则表达式以捕获多个条件
【发布时间】:2019-08-25 17:08:31
【问题描述】:

目前有以下正则表达式来捕获方括号内的所有内容:

regex = /[^[\]]+(?=])/g

意思是:

 string = "[Foo: Bar] [Biz: Baz]"
 string.match(regex) 

在 JavaScript 中会返回:["Foo: Bar", "Biz: Baz"]

下一步,我只想获取冒号后面的文本。可以安全地假设,在所有匹配中,我们将始终有一个返回,其中返回数组中的每个字符串都与上述模式匹配。

我确信有一些方法可以扩展我的正则表达式,以便在查找方括号内的文本的同时做到这一点,但我只是不知道该怎么做。我尝试过使用一些积极的前瞻,但我不知道在哪里添加它们。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    另一种简单的方法:

    const regex = /\[(\w+)\s*:\s*(\w+)\]/g;
    const string = "[Foo: Bar] [Biz: Baz]";
    let match;
    
    while(match = regex.exec(string)){
      console.log(`Pro: ${match[1]}`)
      console.log(`Val: ${match[2]}`)
    }

    【讨论】:

      【解决方案2】:

      您可以添加:) 或(: ),如果您还需要匹配冒号后的空格):

      var string = "[Foo: Bar] [Biz: Baz]"
      
      var regex = /[^[\]:]+(?=])/g;
      
      console.log(string.match(regex));

      【讨论】:

      • : ) 为什么是文字空间? :\s*) 我觉得会更好
      • 我认为你不需要在字符类中包含space,否则对于[Foo: Bar hello] [Biz: Baz]这样的字符串会失败
      【解决方案3】:

      你可以试试这样的

      \[([^:]+:\s*)([^\]]+)
      

      let regex = /\[([^:]+:\s*)([^\]]+)\]/g
      let arr = []
      let string = "[Foo: Bar] [Biz: Baz]"
      
      while((arr =regex.exec(string))!== null){
        console.log(`key -> ${arr[1]}`)  
        console.log(`val -> ${arr[2]}`)
      }

      【讨论】:

        猜你喜欢
        • 2021-01-30
        • 2012-10-19
        • 2013-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-07-11
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        相关资源
        最近更新 更多