Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex satisfying multiple conditions

Tags:

regex

First of all, I have found several examples relating to my query. But none of them was helpful.

Could you please help me to create a regex which satisfies following 3 conditions:

  1. String must contain exactly one alphabetic character
  2. String must contain digits
  3. String must be 9 length

I believe following regex can be used to validate the 3rd condition: \A(?=\w{9,9}\z)

But I was unable to figure out how to combine multiple conditions.

like image 527
Siju Mohan MM Avatar asked Nov 23 '25 01:11

Siju Mohan MM


1 Answers

You can use the following regex:

^(?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*)(?=.*[0-9].*).{9}$

Or, if you do not allow anything other than digits and letters:

^(?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*)(?=.*[0-9].*)[0-9a-zA-Z]{9}$

Demo.

Explanation:

  • ^ - String start
  • (?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*) - Ensure there is only 1 letter in the 9-character string
  • (?=.*[0-9].*) - Ensure that there are digits
  • [0-9a-zA-Z]{9} - The string is 9 characters long (only allowing numbers and characters) (or .{9} - will allow any characters)
  • $ - String end

Mind that [^\r\n] is added for a more reliable testing on regex101, if you test individual strings (not multiline lists), you can just use ^(?=[^a-zA-Z]*[a-zA-Z][^a-zA-Z]*)(?=.*[0-9].*)[0-9a-zA-Z]{9}$.

function isValidPassword(str) {
   return /^(?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*$)(?=.*[0-9].*$)[0-9a-zA-Z]{9}$/.test(str);
}

document.getElementById("res").innerHTML = "3445345f3 is " + isValidPassword('3445345f3') + "<br>222222222 is " + isValidPassword("222222222");
<div id="res"/>
like image 105
Wiktor Stribiżew Avatar answered Nov 24 '25 13:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!