How to create a Regex to find exact String length?

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.

Answers


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


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


Just add a start and end to your regex:

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

The ^ means "beginning of string" The $ means "end of string"

Therefore, there can only be 15 numbers in the string.

For more regex operators in Java, see the Pattern documentation


Need Your Help

UITableViewCell with autolayout left margin different on iPhone and iPad

ios uitableview autolayout margin

I am using a grouped UITableView with static cells for an options screen/scene. Everything is done in Xcode 6.1 / iOS 8.1.x / Storyboard using Autolayout. Within the table groups there are mixed ty...

ASP.NET Windows Authentication

asp.net authentication

I have an ASP.NET website set up using Windows authentication. Each time I open IE and try to access the webpage I get a windows authentication screen. Once I have logged in I can see the website ...