Match words not beginning with &
I need a regex that can match words (case insensitive) that do not begin with & character
For example search string Foo
Then match would be something like:
Use a negative lookbehind assertion like below,
(?i)(?<!&)foo
Explanation:
(?i)
Case insensitive modifier. (?<!&)
Negative lookbehind asserts that the match would be preceded by any but not of &
character. foo
matches the string foo DEMO
For js,
/(?:[^&]|^)(foo)/igm
Get the string you want from group index 1.
DEMO
> var s = "Foo $Foo %Foo &Foo Foo";
undefined
> var re = /(?:[^&]|^)(foo)/igm;
undefined
> var m;
undefined
> while ((m = re.exec(s)) != null) {
... console.log(m[1]);
... }
Foo
Foo
Foo
Foo
Through string.replace
method.
> var s = "Foo $Foo %Foo &Foo Foo";
undefined
> s.replace(/([^&]|^)(foo)/igm, "$1bar")
'bar $bar %bar &Foo bar'
This should be Javascript-friendly for a pattern. It uses non-capture groups and makes sure that foo
is not preceeded by an ampersand (&)
(?:[^&])[fF][oO][oO]
Non-foo characters that are NOT ampersand will show up in the match, but not in the results/capture.
EDIT: You may use the 'i' flag in your javascript regex syntax to invoke the case-insensitive mode modiefer. Then the pattern would just be (?:[^&])foo
上一篇: 如果某件事没有其他事情发生,就匹配
下一篇: 匹配字词不以&开头,