Danilo M.
Danilo M.

Reputation: 1592

Validating numeric sequence

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?

Upvotes: 3

Views: 170

Answers (3)

Reimeus
Reimeus

Reputation: 159754

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}")

Upvotes: 6

harsh
harsh

Reputation: 7692

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}");

Upvotes: 2

Adam Siemion
Adam Siemion

Reputation: 16029

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

should be

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

Upvotes: 7

Related Questions