我有this regex:
/(\[.*?\])/g
现在我想更改该正则表达式以匹配除current-matches之外的所有内容。我怎么能这样做?
例如:
当前正则表达式:
here is some text [anything123][/21something] and here is too [sometext][/afewtext] and here
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
我想要这个:
here is some text [anything123][/21something] and here is too [sometext][/afewtext] and here
// ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ ^^^^^^^^^
答案 0 :(得分:2)
匹配内部的内容或捕获 the trick
之外的内容\[.*?\]|([^[]+)
<强>演示:强>
var str = 'here is some text [anything123][/21something] and here is too [sometext][/afewtext] and here';
var regex = /\[.*?\]|([^[]+)/g;
var res = '';
// Do this until there is a match
while(m = regex.exec(str)) {
// If first captured group present
if(m[1]) {
// Append match to the result string
res += m[1];
}
}
console.log(res);
document.body.innerHTML = res; // For DEMO purpose only