1

I'm looking for a regex which requires both alphabetic and numeric characters (not just numeric or just alphabetic) and is a specific length.

I know this could be done by using two regex or other program code to check the length, but I want to know if it's possible just by using one regex.

This captures both but isn't limited by length.

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

This unfortunately doesn't work

(([0-9]+[a-z]+|[a-z]+[0-9]+)[0-9a-z]){10}
F. Rakes
  • 1,487
  • 3
  • 17
  • 25

2 Answers2

2

you can use positive look-ahead ?= to verify the presence of alphabets and digits and capture both using limit {10}

^(?=.*\d)(?=.*[a-zA-Z])([a-zA-Z\d]{10}$)

Demo

const regex = /^(?=.*\d)(?=.*[a-zA-Z])([a-zA-Z\d]{10}$)/;
console.log(regex.test('abcdefghi9'));
console.log(regex.test('211212jknN'));
console.log(regex.test('211212jknnd')); // extra length 
console.log(regex.test('2121212122'));  // no alphabets
console.log(regex.test('csdcdcdcdc'));   // no digits

update : To find all the matches in single line use

\b(?=[a-zA-Z]+\d|\d+[a-zA-Z])[a-zA-Z\d]{10}\b

(?=[a-zA-Z]+\d : either one or more a-zA-Z and a digit

|\d+[a-zA-Z]) : or one or more digits and one a-zA-Z

Demo

const regex = /\b(?=[a-zA-Z]+\d|\d+[a-zA-Z])[a-zA-Z\d]{10}\b/g;
const str = 'sasas12212 aaaaaaaaaa 211212jknn 211212jknnd 2121212122 csdcdcdcd1 csdcdcdc12';
console.log(str.match(regex));
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • The remaining problem I have is - what I didn't clarify in my question - when the text string contains many other words or just spaces. For instance `regex.test('abcdefghij 1234')` with the added space would get a match. (Omitting the `^` and `$`) – F. Rakes Mar 14 '17 at 19:49
  • To clarify via [demo](https://regex101.com/r/vfhqEO/1) when the string is not multi-line and contains spaces – F. Rakes Mar 15 '17 at 13:50
  • 1
    Amazing, that's exactly what I was trying to do. – F. Rakes Mar 15 '17 at 16:39
0

try something like this. this case Length=3

^(?=.{3,3}$)[a-zA-Z0-9]*(?:_[a-zA-Z0-9]+)*$
Krishna
  • 529
  • 3
  • 13