[英]How to match a range of string that doesn't contain an specific word using only regular expression?
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? 是否可以使用
str.match()
方法使用正则表达式进行匹配?
This seems to work: 这似乎可行:
var regex = /\\[(?!dog)([az]+) (?!dog)([az]+)\\]/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)([az]+) ?){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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.