3

I would like to generate a regex for a string like "S67-90". I used a syntax "String pattern = "\w\d\d\W\d\d"", but I would like to specify that the first word character should always start wit "S". Can anybody please help me with this?

My sample code is :

                      String pattern = "\\w\\d\\d\\W\\d\\d";
                      Pattern p = Pattern.compile((pattern));
                      Matcher m = p.matcher(result);
                      if (m.find()) {
                      System.out.println("Yes!It is!");
                       }
                     else{
                     System.out.println("No!Its not  :(");
                         }

4 Answers 4

5

Just replace first \\w with S in your pattern.

  String pattern = "S\\d\\d\\W\\d\\d";
Sign up to request clarification or add additional context in comments.

1 Comment

Awww..! Thank you..! I already tried this one but was not sure if I was right.
3

If you want your match to start with the letter S, you can do as above. However, if you want to specify that the string must start with an S, you must do this: ^S\\d\\d\\W\\d\\d. This will instruct the regex engine to start matching from the beginning. This regex: S\\d\\d\\W\\d\\d will match bla bla S67-90. This regex: ^S\\d\\d\\W\\d\\d will match only strings starting with S, so it will match only S67-90.

2 Comments

Superrr..!! This works as well. I was looking for this exactly! Thanks!
@dmurali: You could also refactor your regex to something like this: ^S\\d{2}\\W\\d{2}. This should do the same work as the one you proposed, just less verbose. If this answer answered your query, then just mark it so :)
3

Easy, put an "S": String pattern = "[S]\\d\\d\\W\\d\\d";

Comments

0

Simply change first \w to S

S\d\d\W\d\d

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.