简体   繁体   English

正则表达式不匹配字符串中的模式

[英]Regex to not match a pattern in string

I am a newbie and have been struggling the last hour to figure this out. 我是新手,在最后一个小时内一直在努力解决这个问题。 Let's say you have these strings: 假设您有以下字符串:

baa cec haw heef baas bat jackaay

I want to match all the words which don't have two aa's consecutively, so in the above it will match cec , haw , heef , bat . 我想连续匹配所有不具有两个aa的单词,因此在上面它将匹配cechawheefbat

This is what i have done so far, but it's completely wrong i can sense :D 这是我到目前为止所做的,但是我能感觉到的是完全错误的:D

\w*[^\s]*[^a\s]{2}[^\s]*\w*

You maybe want to use negative lookahead: 您可能要使用负前瞻:

/(^|\s)(?!\w*aa\w*)(\w+)/gi

You can check your string by paste this code on console on Chrome/Firefox (F12): 您可以通过在Chrome / Firefox(F12)的控制台上粘贴以下代码来检查字符串:

var pattern = /(^|\s)(?!\w*aa\w*)(\w+)/gi;
var str = 'baa cec haw heef baas bat jackaay';
while(match = pattern.exec(str))
    console.log(match[2]); // position 2 is (\w+) in regex

You can read more about lookahead here . 您可以在此处阅读有关前瞻的更多信息。 See it on Regex101 to see how this regex work. 在Regex101上查看以了解此regex的工作原理。

You need a regex that has 2 things: a word boundary \\b and a negative lookahead right after it (it will be sort of anchored that way) that will lay restrictions to the subpattern that follows. 您需要一个包含两点的正则表达式:单词边界\\b和紧跟其后的负前瞻(它将以这种方式锚定),这将对后面的子模式施加限制。

\b(?!\w*aa)\w+

See the regex demo 正则表达式演示

Regex breakdown: 正则表达式细分:

  • \\b - word boundary \\b单词边界
  • (?!\\w*aa) - the negative lookahead that will cancel a match if the word has 0 or more word characters followed by two a s (?!\\w*aa) -如果单词包含0个或多个单词字符,后跟两个a ,则匹配项将取消匹配
  • \\w+ - 1 or more word characters. \\w+ -1个或更多文字字符。

Code demo: 代码演示:

 var re = /\\b(?!\\w*aa)\\w+/gi; var str = 'baa cec haw heef bAas bat jackaay bar ha aa lar'; var res = str.match(re); document.write(JSON.stringify(res)); 

in javascript, you could use filter and regex invert ! 在javascript中,您可以使用filter和regex invert ! a non-capturing group ?: . 一个非捕获组?:

var strings = ['baa','cec','haw','heef','baas','bat','jackaay'];
strings = $(strings).filter(function(index, element){
   return !/.*(?:aa).*/.test(element);                // regex => .*(?:aa).*
});

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

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