3

I want to write a regex where a string has (9 characters) and start with either "g" or "r" and then are all numbers afterward.

I have written this but it does not work:

public static void main(String[] args) {
    String id= "g57895452";
    String pattern = "/^g([0-9]+){8}$/";
    if (id.matches(pattern)) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}
1
  • 2
    Instead of your if you can simply use System.out.println(id.matches(pattern)). Commented Jul 3, 2012 at 10:25

2 Answers 2

6

Corrected re:

"^[gr]([0-9]{8})$"

You need not + when you already has {8}.

Also you don't need () when you don't want to use the group further in the code.

"^[gr][0-9]{8}$"
Sign up to request clarification or add additional context in comments.

2 Comments

it alwasy gives false for the given id,it is not returning true
@JaneRaj: Remove the slashes please
1

Remove the / from start and end of your regex pattern, It will work.

1 Comment

True, but that's not the only problem.

Your Answer

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