Reputation: 1943
I have a string like this.
var str = "[cat dog] [dog cow] [cow cat] [cat tiger] [tiger lion] [monkey dog]";
I want to match the pair of animals that doesn't contain a specific one. For example I want to select all pair of animals that doesn't contain dog. So the output should be
[cow cat]
[cat tiger]
[tiger lion]
Is it possible to match using Regular Expression using str.match()
method?
Upvotes: 0
Views: 90
Reputation: 44107
This seems to work:
var regex = /\[(?!dog)([a-z]+) (?!dog)([a-z]+)\]/gi;
var string = "[cat dog] [dog cow] [cow cat] [cat tiger] [tiger lion] [monkey dog]";
console.log(string.match(regex));
The above regex matches only two animals in each pair of brackets - this one matches one or more:
var regex = /\[((?!dog)([a-z]+) ?){2,}\]/gi;
var string = "[cat dog] [dog cow] [cow cat] [cat tiger] [tiger lion] [monkey dog] [one animal two animal three animal]";
console.log(string.match(regex));
Upvotes: 1