Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Check if multiple patterns apply to string

I have a set of patterns and I want to check if all of them apply to at least one character in a string. The patterns I am using are: [a-z],[A-Z],[0-9] and [^a-zA-Z0-9- ]. I plan to assemble these into a basic if statement such as:

If ((pattern1,pattern2,pattern3).test(string) == true) {
    //Do Something
}

For example, if I were to use the string dA2#, it would return true since all of the patterns apply to the string, however, if I were to use the string svI2, it would return false since only 3 of the 4 patterns apply.

Please keep in mind that I am new to regex and am not fully familiar with how all of the operators work.

like image 232
Sheep Avatar asked Jun 08 '26 21:06

Sheep


1 Answers

Use this: (?=.*[a-z]). String multiple together like this: (?=.*[a-z])(?=.*[A-Z])

check("a") // does not match
check("aA") // does not match
check("aA1") // does not match
check("aA1&") // matches
check("&Aa1") // matches

function check (string) {
  if (/(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9- ])/.test(string)) {
    console.log("matches", string)
  } else {
    console.log("does not match", string)
  }
}
like image 178
Richard Henage Avatar answered Jun 10 '26 10:06

Richard Henage



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!