How to create a regex to find the exact length of a string?

Having these cases:

  • 12345678901234
  • 123456789012345
  • 1234567890123456
  • 12345678901234567

I need to find a String with an exact length of 15 characters.

So far I have 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 as follows:

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

How to create a regex that can give me the exact result 15, as I thought this regex could give me. More than 15 is unacceptable.

+5
source share
3 answers

Just use matches() instead of 'find ()'

+2
source

Mark the beginning and end of the line with the ^ and $ anchors:

 String pattern = "^([0-9]{15})$"; 
  • ^ matches the position at the beginning of the line
  • $ matches position at end of line

Without these anchors, you are only looking for 15 consecutive digits within a string. Corresponding lines may additionally contain more digits (or even contain letters), although they still match.

(In addition, your inner pair of brackets is redundant - I deleted it. If you get access to the value of the entire match, and not to the value removed by the first group, you can even release other parentheses: T25>)

Regex101 demo

+8
source

Just add a start and end to your regex:

 ^(([0-9]){15})$ 

^ means "start of line"
$ means end of line

Therefore, there can only be 15 numbers in a line.

For more regular statements in Java, see Pattern documentation.

+3
source

Source: https://habr.com/ru/post/1241583/


All Articles