Reputation: 31
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
.
This is what i have done so far, but it's completely wrong i can sense :D
\w*[^\s]*[^a\s]{2}[^\s]*\w*
Upvotes: 0
Views: 230
Reputation: 112
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):
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.
Upvotes: 1
Reputation: 627537
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(?!\w*aa)\w+
See the regex demo
Regex breakdown:
\b
- word boundary(?!\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+
- 1 or more word characters.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));
Upvotes: 1
Reputation: 15164
in javascript, you could use filter
and 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).*
});
Upvotes: 0