0

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, your method works, however, when i use Matcher.find() twice, it return me two different result.
for example : System.out.println( m.find() ) ; return m.find();
The first find will return true, the second one will return false
yes, i am wondering why this would happened, since I've pass the pattern and value to matcher
|
1

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

1 Comment

you answer works good too. I am using the Pattern and Matcher library for my string matching though. didn't know such method works without the library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.