Basically my question is this, why is:
String word = "unauthenticated";
word.matches("[a-z]");
returning false? (Developed in java1.6)
Basically I want to see if a string passed to me has alpha chars in it.
String. contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.
You can use the Pattern. matches() method to quickly check if a text (String) matches a given regular expression. Or you can compile a Pattern instance using Pattern. compile() which can be used multiple times to match the regular expression against multiple texts.
The String.matches()
function matches your regular expression against the whole string (as if your regex had ^
at the start and $
at the end). If you want to search for a regular expression somewhere within a string, use Matcher.find()
.
The correct method depends on what you want to do:
String.matches()
with [a-z]+
)Matcher.find()
with [a-z]
)Your code is checking to see if the word matches one character. What you want to check is if the word matches any number of alphabetic characters like the following:
word.matches("[a-z]+");
with [a-z]
you math for ONE character.
What you’re probably looking for is [a-z]*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With