Java regex for string

I would like to create a regex for a string like "S67-90". I used the syntax "String pattern =" \ w \ d \ d \ W \ d \ d ", but I would like to point out that the character of the first word should always start with" S ". Can anyone help me with this?

My example code:

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

      

+3


source to share


4 answers


If you want your match to start with a letter S

, you can do as above. However, if you want to specify that the string must begin with S

, you should do this: ^S\\d\\d\\W\\d\\d

. This will instruct the regex engine to start matching from the beginning. This is a regex: S\\d\\d\\W\\d\\d

will match bla bla S67-90

. This is a regex: ^S\\d\\d\\W\\d\\d

will only match lines starting with S

, so it will only match S67-90

.



+3


source


Just replace first \\w

with S

in your template.



  String pattern = "S\\d\\d\\W\\d\\d";

      

+5


source


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

+3


source


Just change first \ w to S

S\d\d\W\d\d

      

0


source







All Articles