-2
package regEx;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReGex {

    public static void main(String[] args) {

        String[] s = {"asd", "123", "123abc", "@#$", "ASSF"};
        Pattern p = Pattern.compile("^[A-Z]*[a-z]*[0-9]*+$");
        for (String s1 : s) {
            Matcher m = p.matcher(s1);
            if (m.find()) {
                System.out.println(s1);
            }
        }
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

1 Answers1

2

Why not just s1.matches("[A-Za-z0-9]+") instead :

String[] s = {"asd", "123", "123abc", "@#$", "ASSF"};
for (String s1 : s) {
    if (s1.matches("[A-Za-z0-9]+")) {
        System.out.println(s1);
    }
}

Your regex ^[A-Z]*[a-z]*[0-9]*+$ not mean to match alphanumeric strings, it means :

  • ^ start of string
  • should start with zero or more Upper Letter [A-Z]*
  • followed by zero or more Lower Letter [a-z]*
  • followed by zero or more degits [0-9]*
  • + i don't see why this
  • $ end of string

Edit

I think you mean the input should contains both alphabets and numbers in this case you can use this regex instead (?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+):

if (s1.matches("(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)")) {
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140