Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for java's String.matches method?

Tags:

java

string

regex

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.

like image 381
sMaN Avatar asked Dec 10 '10 02:12

sMaN


People also ask

Can you use .contains with regex?

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.

How do you check if a string matches a pattern in Java?

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.


3 Answers

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:

  1. Check to see whether your input string consists entirely of alphabetic characters (String.matches() with [a-z]+)
  2. Check to see whether your input string contains any alphabetic character (and perhaps some others) (Matcher.find() with [a-z])
like image 105
Greg Hewgill Avatar answered Oct 04 '22 23:10

Greg Hewgill


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]+");
like image 42
jjnguy Avatar answered Oct 05 '22 00:10

jjnguy


with [a-z] you math for ONE character.

What you’re probably looking for is [a-z]*

like image 23
Kissaki Avatar answered Oct 04 '22 23:10

Kissaki