hiboss
hiboss

Reputation: 317

Java regex pattern matching

I want to match the following string pattern for my code. the string value is fixed as below:

630512-07-5847

Pattern p = Pattern.compile("(\\d{6,6})-(\\d{2,2})-(\\d{4,4})");

I've tried the code above, however, when it has more number such as "630512312-07-5847" , it still return true

Upvotes: 0

Views: 114

Answers (2)

Dale
Dale

Reputation: 191

Are you tried actually?

public class Test {
    public static void main(String[] args) {
        System.out.println("630512312-07-5847".matches("(\\d{6,6})-(\\d{2,2})-(\\d{4,4})"));
    }
}

the result is false, bad question

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44854

try

^\\d{6}-\\d{2}-\\d{4}$

This will make sure the if the match begins and end with the entire string,

so

  • 630512-07-5847 - OK
  • 630512-07-58472 - NOT OK
  • 1630512-07-5847 - NOT OK

Upvotes: 2

Related Questions