2

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.

Demo

1
  • I suppose you didn't mean to use those ^ and $ anchors? Commented Jun 19, 2015 at 10:38

1 Answer 1

1

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])

DEMO

Sign up to request clarification or add additional context in comments.

9 Comments

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?
You need to use exec function to get the value from group index 1.
This is result of exec ["foo", undefined, index: 0, input: "foobarfoobarbarfoo"].Why it match foo ?
It does matching foo or bar but captures only the text other than foo or bar. Check my update..
Your exec solution doesn't work ad example with foobarba
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.