Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to test if a String contains both letters and numbers

Tags:

java

regex

I need a regex which will satisfy both conditions.

It should give me true only when a String contains both A-Z and 0-9.

Here's what I've tried:

if PNo[0].matches("^[A-Z0-9]+$")

It does not work.

like image 699
Lucky Avatar asked Jul 18 '12 02:07

Lucky


2 Answers

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.

like image 139
nhahtdh Avatar answered Oct 15 '22 06:10

nhahtdh


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);
}
like image 42
jahroy Avatar answered Oct 15 '22 06:10

jahroy