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.
CodePudding user response:
Use this: (?=.*[a-z])
. String multiple together like this: (?=.*[a-z])(?=.*[A-Z])
check("aBcD123")
check("&Aa1")
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)
}
}
CodePudding user response:
You can do it with the function every
:
The
every()
method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
In our case, it will look like this:
const patterns = [
".*[a-z]",
".*[A-Z]",
".*[0-9]",
".*[^a-zA-Z0-9- ]"
]
const check = (source, patterns) =>
patterns.every(pattern => new RegExp(pattern).test(source));
console.log("dA2#", check("dA2#", patterns))
console.log("svI2", check("svI2", patterns))
console.log("aBcD123", check("aBcD123", patterns))
console.log("&Aa1", check("&Aa1", patterns))