Reputation: 705
I have a line of Java code
System.out.println("...Somtime".matches("^[^a-zA-Z]"));
Which returns false. Why? Can any one help?
Upvotes: 0
Views: 120
Reputation: 1046
String.matches("regex")
This method will match the regex against the WHOLE string. If the string matches regex, it will return true
and false
otherwise
System.out.println("...Somtime".matches("^[^a-zA-Z]{3}[a-zA-Z]+"));
here for three dots you are using {3} and this return true
System.out.println("Somtime".matches("^[^a-zA-Z]"));
it return false
Upvotes: 3
Reputation: 213243
String#matches
matches at both the ends, so your pattern should cover the complete string. And also you don't need to give those anchors (Caret - ^)
at the beginning. It is implicit.
Now, since your first three characters matches - [^a-zA-Z]
, while the later characters matches - [a-zA-Z]
.
So, probably you want: -
"...Somtime".matches("[^a-zA-Z]{3}[a-zA-Z]+")
Upvotes: 5