如何匹配除匹配值以外的所有内容?

时间:2016-02-28 12:56:14

标签: javascript regex

我有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
// ^^^^^^^^^^^^^^^^^^                           ^^^^^^^^^^^^^^^^^                     ^^^^^^^^^

1 个答案:

答案 0 :(得分:2)

匹配内部的内容或捕获 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

相关问题