Regular Expression With Asterisk Quantifier
Solution 1:
var regex = /r*/;
var str = "rodriguez";
The regex engine will first try to match r
in rodriguez
from left to right and since there is a match, it consumes this match.
The regex engine then tries to match another r
, but the next character is o
, so it stops there.
Without the global flag g
(used as so var regex = /r*/g;
), the regex engine will stop looking for more matches once the regex is satisfied.
Try using:
var regex = /a*/;
var str = "cabbage";
The match will be an empty string, despite having a
s in the string! This is because at first, the regex engine tries to find a
in cabbage
from left to right, but the first character is c
. Since this doesn't match, the regex tries to match 0 times. The regex is thus satisfied and the matching ends here.
It might be worth pointing out that *
alone is greedy, which means it will first try to match as many as possible (the 'or more' part from the description) before trying to match 0 times.
To get all r
from rodriguez
, you will need the global flag as mentioned earlier:
var regex = /r*/g;
var str = "rodriguez";
You'll get all the r
, plus all the empty strings inside, since *
also matches 'nothing'.
Solution 2:
Use global switch to match 1 or more r anywhere in the string:
var regex = /r+/g;
In your other regex:
var regex = /<[A-Za-z][A-Za-z0-9]*>/;
You're matching literal <
followed by a letter followed by 0 or more letter or digits and it will perfectly match <html>
But if you have input as <foo>:<bar>:<abc>
then it will just match <foo>
not other segments. To match all segments you need to use /<[A-Za-z][A-Za-z0-9]*>/g
with global switch.
Post a Comment for "Regular Expression With Asterisk Quantifier"