Reputation: 4266
Somehow
var regex=/a(?i)b/;
lets the JS console in Firefox tell me "invalid quantifier". Do you know what's wrong about it?
UPDATE:
I just saw at http://regex101.com/r/iW3kE7 that (?i) seems not to work in JS (but in php). How do I do such things like local modifiers in JS?
I'm trying to introduce case insensitivity by (?i).
Upvotes: 0
Views: 58
Reputation: 1074198
Answer to updated question:
I'm trying to introduce case insensitivity by
(?i)
.
You can't do that in JavaScript, the expression as a whole is either case-sensitive, or not. You get a case-insensitive expression by using the i
flag at the end:
var rex = /expression/i;
So if your goal is to match a
(in lower case) followed by b
or B
, the expression would be:
var rex = /a[bB]/;
I'm sure your actual use case isn't that simple and so this is going to complicate things fairly significantly for your real expression, but unfortunately there just isn't a way to start out being case-sensitive and then switch to being case-insensitive part-way through. You either have to do the character class thing (above), or split it into multiple expressions and then make sure matches for the first one are followed immediately by matches for the second one. In fact, you could probably create a utility function/object that accepts a series of regular expressions, and looks for matches for the expressions adjacent to each other, e.g.:
var matcher = new MyNiftyMatcherThing(/a/, /b/i);
if (matcher.exec(someString)) {
// ...
}
Answer before clarification of question:
The ?
(a quantifier meaning "zero or one") has to refer to something in front of it, but there's nothing in front of it in the capture group for it to refer to.
You haven't said what you're doing, but if the goal is to either have or not have an i
between a
and b
, and capture it if it's there, you just have the characters reversed:
var regex=/a(i?)b/;
If your goal was to make the i
optional without capturing it, you'd combine the quantifier with a non-capturing group (so it only applies to the i
, not the a
):
var regex=/a(?:i?)b/;
If your goal was to have a non-capturing group (although I'm not quite sure why you'd need one just for the letter i
), you need a :
after the ?
:
var regex=/a(?:i)b/;
(Or there's (?=...)
for a positive lookahead, or (?!...)
for a negative lookahead.)
Upvotes: 2
Reputation: 174696
Put the ?
outside the brackets to make it optional,
var regex=/a(i)?b/;
It matches ab
or aib
. If aib
is present in your input then i
is stored into a group. After that you can refer i
through backreference.
Upvotes: 0
Reputation: 75555
If you are trying to match a
followed by an optional i
, followed by b
, then the correct syntax is to put the quantifier ?
after i
.
var regex=/a(i?)b/;
As TJ Crwoder mentioned in his answer, ?
in your expression is not quanifying anything so it is consequently invalid.
Upvotes: 0