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 accep开发者_C百科ted
Special characters are not allowed.
([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.
This is Python, same pattern ought to work in Java:
>>> import re
>>> re.compile('[0-9a-z]*[0-9][0-9a-z]*[a-z][0-9a-z]*|[0-9a-z]*[a-z][0-9a-z]*[0-9][0-9a-z]*', re.I)
<_sre.SRE_Pattern object at 0x830fbd0>
>>> p=_
>>> for s in '1a1b23nh', 'bc112w', 'abc', '123':
... print s, p.match(s)
...
1a1b23nh <_sre.SRE_Match object at 0xb73a3d78>
bc112w <_sre.SRE_Match object at 0xb73a3d78>
abc None
123 None
on 2nd thought, better add '$' at the end, or it will match 'ab12/'
sorry for the javascript example I would break it down to avoid a hard to read regex.
function valid(s) {
return /^[a-z0-9]+$/i.test(s) &&
/[a-z]+/i.test(s) &&
/[0-9]+/.test(s)
}
valid('123a87') ; //# => true
valid('A982') ; //# => true
valid('$54 ') ; //# => false
valid('123') ; //# => false
valid('abd') ; //# => false
精彩评论