Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Regex to find exact String length?

Tags:

java

regex

Having these cases:

  • 12345678901234
  • 123456789012345
  • 1234567890123456
  • 12345678901234567

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:

  • 12345678901234 (not found which is GOOD)
  • 123456789012345 (found which is GOOD)
  • 1234567890123456 (found which is NOT GOOD)
  • 12345678901234567 (found which is NOT GOOD)

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.

like image 916
The Dr. Avatar asked Dec 18 '22 20:12

The Dr.


1 Answers

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 string

Without 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

like image 130
Marius Schulz Avatar answered Dec 21 '22 09:12

Marius Schulz