正则表达式:匹配所有字符串,但捕获两个符号之间的组

时间:2018-07-18 05:00:52

标签: javascript regex split

问题:

给出以下字符串:

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>>"]

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

4 个答案:

答案 0 :(得分:4)

这里是一个选项-将<<匹配到>>并包括在内,或者将字符匹配到前行匹配<<或字符串末尾的位置:

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

答案 1 :(得分:1)

<<...>>

分割

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

const r = str.split(/(<<[^<>]+>>)/g)

console.log(r)

答案 2 :(得分:1)

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

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

或者如果您希望包含<<>>,请将它们添加到您的匹配组中

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

答案 3 :(得分:1)

<<...>>分隔并使用.filter(Boolean)过滤出空值。

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

const r = str.split(/(<<[^<>]+>>)/g).filter(Boolean)

console.log(r)