Regular expression for alphanumeric

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

This should work for:

"1a1b23nh" Accepted

"bc112w" Accepted

"abc" Not accepted

"123" Not accepted

Special characters are not allowed.

+6
source share
5 answers
(([az]+[0-9]+)+|(([0-9]+[az]+)+))[0-9a-z]* 

How about a simple content check? Check if there is a number 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 } 
+3
source
 ([0-9]+[a-zA-Z][0-9a-zA-Z]*)|([a-zA-Z]+[0-9][0-9a-zA-Z]*) 
+5
source

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

 Pattern pattern = Pattern.compile("(?i)(?:((?:\\d+[az]+)|(?:[az]+\\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.

+2
source

This is Python, the same template should work in Java:

 >>> import re >>> re.compile('[0-9a-z]*[0-9][0-9a-z]*[az][0-9a-z]*|[0-9a-z]*[az][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, it is better to add '$' at the end, or it will match 'ab12 /'

0
source

sorry for the javascript example I would break it to avoid a regex difficult to read.

 function valid(s) { return /^[a-z0-9]+$/i.test(s) && /[az]+/i.test(s) && /[0-9]+/.test(s) } valid('123a87') ; //# => true valid('A982') ; //# => true valid('$54 ') ; //# => false valid('123') ; //# => false valid('abd') ; //# => false 
0
source

Source: https://habr.com/ru/post/890655/


All Articles