如何仅使用正则表达式匹配不包含特定单词的字符串范围?

问题描述 投票:0回答:1

我有这样的字符串。

var str = "[cat dog] [dog cow] [cow cat] [cat tiger] [tiger lion] [monkey dog]";

我想匹配那些不含特定动物的动物。例如,我想选择所有不含狗的动物。所以输出应该是

[cow cat]
[cat tiger]
[tiger lion]

是否可以使用str.match()方法使用正则表达式进行匹配?

javascript regex string
1个回答
1
投票

这似乎有效:

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));

上面的正则表达式只匹配每对括号中的两个动物 - 这个匹配一个或多个:

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));
© www.soinside.com 2019 - 2024. All rights reserved.