开发者

Javascript RegExp - how do I match for a word, but not if another word is also present?

I am testing a string against a series of regular expressions. Most of these are simple - often just testing if a single word开发者_如何学C appears in the string like so

var str = 'Blah blah foo blah';

var my_array = [
    {
        test: 'foo',
        name: 'foo_ame'
    },
    {
        test: 'bar',
        name: 'bar_name'
    }
]

for (var i = 0; i < my_array.length; i++) {
    if (new RegExp(my_array[i].test).test(str)) {
        console.log(my_array[i].name); // foo_name
    }
}

I have one case where I want to match if the string contains 'qux' and not 'foo', eg

for 'blah foo blah'     returns foo_name
for 'blah foo qux blah' returns qux_name (only)

It's only really necessary for this one case out of about 30 so I'd rather not rewrite the loop if I can avoid it. Is it something I can match for with regular expressions?


AFAIK, the only way to do this within one regular expression is to use a lookaround, but it'd be quite bulky because you'd want to catch instances where "foo" precedes or follows "qux". E.g.

/^(?:(?!foo).)*qux(?:(?!foo).)*$/

I would suggest changing the way you test the strings so you can have a positive regex and a negative regex -- i.e. one the string must pass against and one the string must fail against.


I guess you're looking for a "negative lookbehind" (see this very good online help - unfortunately, they say javascript does not support "lookbehinds")

eg. (?<!a)b matches a "b" that is not preceded by an "a"

so in your case:

(?<!foo )qux //don't forget the space after foo
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜