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 :(");
}
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 anS, 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\\dwill matchbla bla S67-90. This regex:^S\\d\\d\\W\\d\\dwill match only strings starting withS, so it will match onlyS67-90.