I am using this regex ^(?:foo|bar)+|(.+)$ to catch string different from 'foo' or 'bar' but it catches string only after foo or bar and not at beginning. For example it catches ba in string foobarfooba but doesn't catch ba in string bafoobarfoo.
1 Answer
Because you used the start of a line anchor. Removing the start of the line anchor also won't work for you. So I suggest you to use the below regex.
var s = "bafoobar";
var re = /foo|bar|((?:(?!foo|bar).)+)/gm;
alert(re.exec(s)[1])
9 Comments
Giuseppe federico
Ok it is perfect ,but I don't understand why with
var patt = new RegExp("foo|bar|((?:(?!foo|bar).)+)"); var res = patt.test(string); console.log(res)//true; and string = foobarfoobarbarfoo why res is true?Avinash Raj
You need to use exec function to get the value from group index 1.
Giuseppe federico
This is result of exec
["foo", undefined, index: 0, input: "foobarfoobarbarfoo"].Why it match foo ?Avinash Raj
It does matching foo or bar but captures only the text other than foo or bar. Check my update..
Giuseppe federico
Your exec solution doesn't work ad example with
foobarba |
^and$anchors?