Having these cases:
I need to find the String which has exact 15 chars length.
Until now I made this code:
String pattern = "(([0-9]){15})";
Mathcer m = new Mathcer(pattern);
if (m.find()){
System.out.println(m.group(1));
}
The results were like this:
How can I create a regex which can give me result of exact 15 like I thought this regex can give me. More then 15 is not acceptable.
Mark the start and the end of the string using the ^
and $
anchors:
String pattern = "^([0-9]{15})$";
^
matches the position at the beginning of the string$
matches the position at the end of the stringWithout these anchors, you're only looking for 15 consecutive digits anywhere within the string. Matching strings can additionally have more digits (or even contain letters), though, and still match.
(Also, your inner pair of parentheses is superfluous — I've removed it. If you're accessing the value of the entire match rather than the value captured by the first group, you can even emit the other parentheses: "^[0-9]{15}$"
)
Regex101 Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With