3

I am using Java and I need to validate a numeric sequence like this: 9999/9999.

I tried using this regex \\d{4}\\\\d{4}, but I am getting false for matches().

My code:

    Pattern regex = Pattern.compile("\\d{4}\\\\d{4}");

    if (!regex.matcher(mySequence).matches()) {
        System.out.println("invalid");
    } else {
        System.out.println("valid");
    }

Can anyone help me, please?

3 Answers 3

7
Pattern regex = Pattern.compile("\\d{4}\\\\d{4}");

should be

Pattern regex = Pattern.compile("\\d{4}/\\d{4}");
Sign up to request clarification or add additional context in comments.

Comments

6

The regex pattern is attempting to match a backslash rather than a forward slash character. You need to use:

Pattern regex = Pattern.compile("\\d{4}/\\d{4}")

Comments

2

Change your pattern to :

Pattern regex = Pattern.compile("\\d{4}\\\\\\d{4}");

for matching "9999\\9999" (actual value: 9999\9999) (in java you need to escape while declaring String)

or if you want to match "9999/9999" then above solutions would work fine:

Pattern regex = Pattern.compile("\\d{4}/\\d{4}");

Comments

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.