Pattern matching a string
I'm trying to pattern match a string in java which has the following syntax:
ENSMUS followed by one character which can be anything followed by 11 digits.
I've done this in javascript using the following regex:
var regex = /^ENSMUS(\w{1})(\d{11})$/;
I'm slightly confused by the Java equivalent (having looked at the Pattern class in the API). Could anyone lend a hand please?
> ...
> ENSMUS followed by one character which can be
> anything followed by 11 digits.
String s = ...
boolean b = s.matches("ENSMUS.\\d{11}");
Note that when matching an entire String, you don't need to provide a beginning (^) and end ($) in your regex. Also, you said "any character", this is not \w, but a . (a period). \w is a "word character".
> > ...
> > ENSMUS followed by one character which can be
> > anything followed by 11 digits.
>
> String s = ...
> boolean b = s.matches("ENSMUS.\\d{11}");
>
> Note that when matching an entire String, you don't
> need to provide a beginning (^) and end ($) in your
> regex. Also, you said "any character", this is not
> \w, but a . (a period). \w is a "word character".
So I assume if it was a word character it would be
String s = ...
boolean b = s.matches("ENSMUS\\w{1}\\d{11}");
I'll try it and see what happens. Thanks
> ...
> So I assume if it was a word character it would be
>
> String s = ...
> boolean b =
> s.matches("ENSMUS\\w{1}\\d{11}");
That is correct (and as masijade suggested).
Also note that within Strings, the \ needs to be escaped, hence the double \\ before the w and d meta-characters. I also omitted the grouping parentheses which are of no use in your case and in combination with the String.matches(...) method.
> I'll try it and see what happens. Thanks
You're welcome.