我有this regex:
/(\[.*?\])/g
现在,我想更改该正则表达式以匹配除当前匹配项之外的所有内容。我怎样才能做到这一点?
例如:
当前正则表达式:
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
// ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ ^^^^^^^^^
最佳答案
匹配内部内容或捕获the trick外的内容
\[.*?\]|([^[]+)
See demo at regex101
演示:
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