Regex not working in String.matches ()

I have this little piece of code

String[] words = {"{apf","hum_","dkoe","12f"}; for(String s:words) { if(s.matches("[az]")) { System.out.println(s); } } 

Supposed to print

 dkoe 

but he doesn't print anything !!

+66
java regex
Jan 19 '12 at 9:02
source share
8 answers

Welcome to the Java method without the name .matches() ... It tries and matches ALL input. Unfortunately, other languages ​​have followed this example :(

If you want to see if the regular expression matches the input text, use the Pattern , a Matcher and .find() method to match:

 Pattern p = Pattern.compile("[az]"); Matcher m = p.matcher(inputstring); if (m.find()) // match 

If you really need to see if the input has only lowercase letters, you can use .matches() , but you need to match one or more characters: add + to your character class, as in [az]+ . Or use ^[az]+$ and .find() .

+162
Jan 19 '12 at 9:08
source share

[az] matches a single char between a and z. So, if your line was just "d" , for example, it would match and print.

You need to change your regular expression to [az]+ to match one or more characters.

+30
Jan 19 2018-12-12T00:
source share

java regex implementation tries to match whole string

which is different from perl regular expressions that try to find the appropriate part

if you want to find a string with nothing but lowercase characters, use the template [az]+

if you want to find a string containing at least one lowercase character, use the pattern .*[az].*

+12
Jan 19 '12 at 9:08
source share

String.matches returns whether the entire string matches the regular expression, and not just any substring.

+10
Jan 19 '12 at 9:08
source share

B

 String[] words = {"{apf","hum_","dkoe","12f"}; for(String s:words) { if(s.matches("[az]+")) { System.out.println(s); } } 
+5
Jan 19 '12 at 9:09
source share

I ran into the same problem:

 Pattern ptr = Pattern.compile("^[a-zA-Z][\\']?[a-zA-Z\\s]+$"); 

The above failed!

 Pattern ptr = Pattern.compile("(^[a-zA-Z][\\']?[a-zA-Z\\s]+$)"); 

The above work with the template within ( ) .

+4
Dec 04 '15 at 4:44
source share

Your regular expression [az] does not match dkoe , since it matches only strings of length 1. Use something like [az]+ .

0
Jan 19 '12 at 9:05
source share

You can make your template case insensitive by doing:

 Pattern p = Pattern.compile("[az]+", Pattern.CASE_INSENSITIVE); 
-2
Mar 14 '14 at 20:53
source share



All Articles