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.
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().
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.
[] 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 .
([0-9]+[a-zA-Z][0-9a-zA-Z]*)|([a-zA-Z]+[0-9][0-9a-zA-Z]*)
(([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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With