0

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?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Adnan Toky
  • 1,756
  • 2
  • 11
  • 19

1 Answers1

1

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));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79