2016-02-28 67 views
1

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

只需使用'replace'更换匹配。 'str.replace(/(\[.*?\])/ g,'')' – Tushar

+0

@Tushar我想知道是否有任何方法来匹配除正则表达式中的模式之外的所有内容? – stack

+0

我会按照Tushar的建议使用替换,这就是我要说的。 – Veverke

回答

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

+1

@stack这是做同样的事情。你只需要获得第一个捕获的组并加入它们。 – Tushar

+0

@Tushar是的我知道'$ 1'的内容正是我所需要的。顺便说一句,我可以做到这一点正如你所说*(使用'.replace()')*,但说实话,我想知道我该怎么做,使用先行'(?!)'? *(因为我看到了某处使用looka的方法)* – stack

+1

@stack添加了演示。 – Tushar

相关问题