简体   繁体   English

regexp以匹配序列(如果不是以特定字符开头和结尾)

[英]regexp to match sequence if not starting and ending with a specific character

When it comes to regexps, I'm not very good at finding one that works and suits my needs.I need to match a word say foo if it is not included between a character say [ and another character say ] 在使用正则表达式时,我不太擅长找到适合我需要的正则表达式。如果在一个字符说[和另一个字符说]之间不包含foo这个词,我需要将其匹配

 "[foo] foo" // I need to replace foo with bar
 // expected result : "[foo] bar" but not "[bar] bar"

I know how to match it if it is not followed by ] 如果不跟[ ],我知道如何匹配

 "foo] foo".replace(/foo(!?\])/g,"bar")

And I also know how to match it if it is not preceded by [ 而且我也知道如何搭配它,如果它不是由前面 [

 " [foo foo".replace(/(\[)?foo/g,function(_0,_1) {
      return _1:_0?"bar"
 })

But I don't know how to put them together.Thank you! 但是我不知道如何将它们放在一起。谢谢!

请尝试使用此词来匹配[和]之间的单词

"[foo] foo".match(/\[.*?\]/g)

You need the following regex: 您需要以下正则表达式:

(?<!\[)foo(?!])

it has negative lookbehind for [ and negative lookahead for ] . 它对[负向后看,对]负向后看。

Using a negative lookahead you can use this regex: 使用负前瞻,您可以使用以下正则表达式:

var repl = str.replace(/\bfoo\b(?![^\]\[]*\])/g, 'bar');

RegEx Demo 正则演示

(?![^\\]\\[]*\\]) is a negative lookahead assertion. (?![^\\]\\[]*\\])是否定的超前断言。 This asserts failure when it finds a ] without matching [ or ] on the way, thus not matching foo inside [...] . 这个断言故障当它找到一个]没有匹配[]上的方式,从而不匹配foo内部[...]

\\b is used for word boundary. \\b用于单词边界。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM