简体   繁体   中英

Regex for java's String.matches method?

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.

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 [az]+ )
  2. Check to see whether your input string contains any alphabetic character (and perhaps some others) ( Matcher.find() with [az] )

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 [az] you math for ONE character.

What you're probably looking for is [az]*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM