忽略带有特殊词的模式

时间:2016-04-15 12:26:03

标签: javascript regex

我有以下代码:

var one = "What a lovely puppy! 
    Is it 
    a beagle?",

    two = "You've got a lovely funny beagle!",

    three = "Where's my lovely dog? Where's my little beagle?";

var target = (".* lovely(?!funny).* beagle.*");

我需要的是“抓住”lovelybeagle之间的字词。如果我的“catch”边界(var funny)之间有单词two,则该方法 match()应该忽略它。

换句话说,它应该检查匹配从lovelybeagle的所有短语,这些短语不涉及单词funny

我的var目标似乎写得不正确。

我期待:

 one.match(target) //return: "puppy! Is it a"
 two.match(target) //must be ignored, because of word "funny"
 three.match(target) //return: "dog? Where's my little"

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

您必须加入funny.*的重复测试。尝试

lovely(?:(?!funny).)*beagle

Check it out here at regex101.

此致

答案 1 :(得分:0)

我建议对第一个字母进行每个字符的检查,然后检查“有趣”,如果当前的字母是初始字母f

var regex = /\blovely\b([^f]|\Bf|f(?!unny\b))+\bbeagle\b/;