0
votes

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:

  • foo
  • Foo
  • Foobar
  • Bar Foo
  • BarFoo
  • Bar Foobar
  • $Foobar
  • $Foo$
  • Foo $Foo %Foo &Foo Foo
2

2 Answers

2
votes

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'
1
votes

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