Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for alphanumeric

Tags:

java

regex

I want a regular expression in java that must contain at least a alphabet and a number at any position. It is for the password that contain the digits as well as numbers.

This should work for:

"1a1b23nh" Accepted

"bc112w" Accepted

"abc" Not accepted

"123" Not accepted

Special characters are not allowed.

like image 918
Amandeep Singh Avatar asked Jun 16 '11 05:06

Amandeep Singh


People also ask

How do I check if a string is alphanumeric regex?

For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re. match(regex, string) using the regex: "^[a-zA-Z0-9]+$". re. match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


3 Answers

([0-9]+[a-zA-Z][0-9a-zA-Z]*)|([a-zA-Z]+[0-9][0-9a-zA-Z]*)
like image 169
Petar Ivanov Avatar answered Nov 03 '22 10:11

Petar Ivanov


(([a-z]+[0-9]+)+|(([0-9]+[a-z]+)+))[0-9a-z]*

How about a simple content check? Check if there are number(s) and character(s)

String input = "b45z4d";
boolean alpha = false;
boolean numeric = false;
boolean accepted = true;
for (int i = 0; i < input.length(); ++i)
{
    char c = input.charAt(i);
    if (Character.isDigit(c))
    {
        numeric = true;
    } else if (Character.isLetter(c))
    {
        alpha = true;
    } else
    {
        accepted = false;
        break;
    }
}

if (accepted && alpha && numeric)
{
    // Then it is correct
}
like image 3
Martijn Courteaux Avatar answered Nov 03 '22 10:11

Martijn Courteaux


I know that the question already have been answered, and accepted, but this is what I would do:

Pattern pattern = Pattern.compile("(?i)(?:((?:\\d+[a-z]+)|(?:[a-z]+\\d+))\\w*)");

Object[][] tests = new Object[][] {
        { "1a1b23nh", Boolean.valueOf(true) },
        { "bc112w", Boolean.valueOf(true) },
        { "abc", Boolean.valueOf(false) },
        { "123", Boolean.valueOf(false) }
};

for (Object[] test : tests) {
    boolean result = pattern.matcher((String)test[0]).matches();
    boolean expected = ((Boolean)test[1]).booleanValue();
    System.out.print(test[0] + (result ? "\t " : "\t not ") + "accepted"); 
    System.out.println(result != expected ? "\t test failed" : "");
}
System.out.println("\nAll checks have been executed");

(?i) makes the regexp case insensitive.

like image 2
Kaj Avatar answered Nov 03 '22 12:11

Kaj