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
.
Asked
Active
Viewed 58 times
2

Giuseppe federico
- 53
- 5
-
I suppose you didn't mean to use those `^` and `$` anchors? – Bergi Jun 19 '15 at 10:38
1 Answers
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])

Avinash Raj
- 172,303
- 28
- 230
- 274
-
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? – Giuseppe federico Jun 19 '15 at 11:05
-
You need to use exec function to get the value from group index 1. – Avinash Raj Jun 19 '15 at 11:07
-
This is result of exec `["foo", undefined, index: 0, input: "foobarfoobarbarfoo"]`.Why it match foo ? – Giuseppe federico Jun 19 '15 at 11:13
-
It does matching foo or bar but captures only the text other than foo or bar. Check my update.. – Avinash Raj Jun 19 '15 at 11:19
-
-
regex is correct. You have to do somethinbg with exec. Than is append each match into an array and printoput only th text ie, not of undefined. – Avinash Raj Jun 19 '15 at 11:38
-
Yes regex is correct, but with foobarba exec returns` ["foo", undefined, index: 0, input: "foobarba"] `? There is no 'ba' – Giuseppe federico Jun 19 '15 at 11:41
-
see it shows you the index 0 not index 1. have a look at this http://stackoverflow.com/a/432503/3297613 – Avinash Raj Jun 19 '15 at 11:42
-
Problem is that it matches also foo and bar. It has to match only word different from them like ba. So the index of exec change everytime depending where ba is. – Giuseppe federico Jun 19 '15 at 12:05