简体   繁体   English

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

[英]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.

相关问题 如何用正则表达式匹配特定的字符串? - How to match a specific string with regular expression? 正则表达式仅在子模式不匹配时匹配 - Regular expression match only if subpattern doesn't match 如何仅使用正则表达式获取字符串的特定部分? - How get only a specific part of a string using a regular expression? 正则表达式仅使用第一个单词来匹配复合词 - Regular Expression to match compound words using only the first word 如何生成不包含任何空格的正则表达式,甚至在字符串的开头或结尾也不包含任何空格 - How to generate Regular Expression that doesn't contain any white space at all and even at the beginning or the end of the string 正则表达式停在特定字符处,不匹配返回null - Regular expression to stop at specific character, return null if doesn't match 如何使用正则表达式匹配精确字符串 - How to match with an exact string using regular expression 使用JavaScript正则表达式风格,如何仅在另一个特定标签内时才匹配特定标签? - Using the JavaScript regular expression flavour, how to match a specific tag only when inside another specific tag? 如何使用JavaScript正则表达式匹配包含两个相同单词的字符串中的单词? - How can i match a word in a string which has two same words before it using JavaScript regular expression? 如何匹配特定的正则表达式? - How to match a specific regular expression?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM