regex – Understanding regular expression in Java

The first part of the regex ([12]) is a character set. It tells to match only one out of several characters.

In your case, the [12] matches the first 1 in your string.

Then, in the regex there is a .. It tells to match any character except line breaks.

In your case, the [12]. match: 12 (The 2 is matched by the .)

Lastly, in the regex ({2}) there is a quantifier. It tells to match X (in your case 2) of the pretending token.

In your case, the [12].{2} match: 121 (The second 1 is matched due the quantifier. Basically is like a double .)


With the string 11a2 the match method returns false because there is no a full match. The regex matches only the 11a and not the 2

Read more here: Source link