java - How to test if a String contains both letter and number

I suspect that the regex below is slowed down by the look-around, but it should work regardless:

.matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")

The regex asserts that there is an uppercase alphabetical character (?=.*[A-Z]) somewhere in the string, and asserts that there is a digit (?=.*[0-9]) somewhere in the string, and then it checks whether everything is either alphabetical character or digit.


It easier to write and read if you use two separate regular expressions:

String s  =  "blah-FOO-test-1-2-3";

String numRegex   = ".*[0-9].*";
String alphaRegex = ".*[A-Z].*";

if (s.matches(numRegex) && s.matches(alphaRegex)) {
    System.out.println("Valid: " + input);
}

Better yet, write a method:

public boolean isValid(String s) {
    String n = ".*[0-9].*";
    String a = ".*[A-Z].*";
    return s.matches(n) && s.matches(a);
}

A letter may be either before or after the digit, so this expression should work:

(([A-Z].*[0-9])|([0-9].*[A-Z]))

Here is a code example that uses this expression:

Pattern p = Pattern.compile("(([A-Z].*[0-9])|([0-9].*[A-Z]))");
Matcher m = p.matcher("AXD123");
boolean b = m.find();
System.out.println(b);

Tags:

Java

Regex