【问题标题】:Regex: Match all string but capture groups between two symbols正则表达式:匹配所有字符串,但捕获两个符号之间的组
【发布时间】:2018-07-18 13:28:36
【问题描述】:

问题:

给定这个字符串:

str = "this is<< just>> an example <<sentence>>"

如何得到以下数组:

arr = ["this is", "<< just>>", " an example ", "<<sentence>>"]

尝试:

我可以拆分字符串,但是这会删除 '>'。

str.split(/<<|>>/)
=> ["this is", " just", " an example ", "sentence"]

我可以匹配“>”之间的文本块,但是这会丢失句子的其余部分。

str.match(/(<{2})(.*?>{2})/g)
=> ["<< just>>", "<<sentence>>"]

如何捕获字符串的其余部分以及单独的捕获组?

【问题讨论】:

    标签: javascript regex split


    【解决方案1】:

    这是一个选项 - 匹配 &lt;&lt; 直到并包括 &gt;&gt;,或者匹配字符直到前瞻匹配 &lt;&lt; 或字符串结尾:

    const str = "this is<< just>> an example <<sentence>> foo";
    const re = /<<.+?>>|.+?(?=<<|$)/g;
    console.log(str.match(re));

    【讨论】:

      【解决方案2】:

      &lt;&lt;...&gt;&gt;分割

      const str = "this is<< just>> an example <<sentence>>"
      
      const r = str.split(/(<<[^<>]+>>)/g)
      
      console.log(r)

      【讨论】:

        【解决方案3】:

        &lt;&lt;...&gt;&gt; 拆分并使用.filter(Boolean) 过滤掉空值。

        const str = "this is<< just>> an example <<sentence>>"
        
        const r = str.split(/(<<[^<>]+>>)/g).filter(Boolean)
        
        console.log(r)

        【讨论】:

          【解决方案4】:

          简单的解决方案 - 将匹配组添加到您的拆分正则表达式中

          var str = "this is<< just>> an example <<sentence>>"
          var result = str.split(/(<<|>>)/)
          console.log(result);

          或者如果您希望包含 &lt;&lt;&gt;&gt;,请将它们添加到您的匹配组中

          /(<<[^>]+>>)/
          

          【讨论】:

            猜你喜欢
            • 2011-08-31
            • 1970-01-01
            • 2019-01-16
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多