我正在尝试将字符串拆分为与正则表达式匹配的字符串数组和不匹配的字符串数组:
string = "Lazy {{some_animal}} jumps over.."
# do some magic with regex /({{\s?[\w]+\s?}})/g and its negation
array = ["Lazy ", "{{some_animal}}", " jumps over.."]
在javascript中以最佳方式执行此操作?
答案 0 :(得分:3)
您可以{/ 3}}使用
下面的正则表达式只匹配任何不是胡须的东西,可选择包围胡须。
示例摘录:
var str = "Lazy {{some_animal}} jumps over..";
const pattern = /\{*[^{}]+\}*/g;
var array = str.match(pattern);
console.log(str);
console.log(pattern);
console.log(array);
但为了使其更精确,正则表达式模式变得有点复杂 下面的正则表达式匹配:
var str = "Lazy {{some_animal}} jumps over..";
const pattern = /\{\{\w+\}\}|.+?(?=\{\{\w+\}\})|.+/g;
var array = str.match(pattern);
console.log(str);
console.log(pattern);
console.log(array);
最后但并非最不重要的是,邪恶的SM方法 拆分和匹配相同的正则表达式。并将它们合并为一个阵列 这种方法的缺点是订单不会被保留。
var str = "Lazy {{some_animal}} jumps over..";
const pattern = /\{\{\w+\}\}/g;
var what_you_want = str.match(pattern);
var what_you_dont_want = str.split(pattern);
var array = what_you_want.concat(what_you_dont_want);
console.log(str);
console.log(pattern);
console.log(array);
答案 1 :(得分:2)
我相当确定一个简单的exec
循环将是您的最佳选择:
function getSegments(rex, str) {
var segments = [];
var lastIndex = 0;
var match;
rex.lastIndex = 0; // In case there's a dangling previous search
while (match = rex.exec(str)) {
if (match.index > lastIndex) {
segments.push(str.substring(lastIndex, match.index));
}
segments.push(match[0]);
lastIndex = match.index + match[0].length;
}
if (lastIndex < str.length) {
segments.push(str.substring(lastIndex));
}
return segments;
}
var rex = /{{\s?[\w]+\s?}}/g;
var string = "Lazy {{some_animal}} jumps over..";
console.log(getSegments(/{{\s?[\w]+\s?}}/g, string));
&#13;
注意我删除了捕获组;这种解决方案不需要它。
答案 2 :(得分:-2)
请尝试使用表达式
/\b\w+\s|{{\b\w*}}|\b\w.+/g