I have this regex to allow for only alphanumeric characters.
How can I check that the string at least contains 3 alphabet characters as well.
My current regex,
if(!/^[a-zA-Z0-9]+$/.test(val))
I want to enforce the string to make sure there is at least 3 consecutive alphabet characters as well so;
111 // false aaa1 // true 11a // false bbc // true 1a1aa // false
. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.
Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.
To enforce three alphabet characters anywhere,
/(.*[a-z]){3}/i
should be sufficient.
Edit. Ah, you'ved edited your question to say the three alphabet characters must be consecutive. I also see that you may want to enforce that all characters should match one of your "accepted" characters. Then, a lookahead may be the cleanest solution:
/^(?.*[a-z]{3})[a-z0-9]+$/i
Note that I am using the case-insensitive modifier /i
in order to avoid having to write a-zA-Z
.
Alternative. You can read more about lookaround assertions here. But it may be a little bit over your head at this stage. Here's an alternative that you may find easier to break down in terms of what you already know:
/^([a-z0-9]*[a-z]){3}[a-z0-9]*$/i
+
means "1 or more occurrences."
{3}
means "3 occurrences."
{3,}
means "3 or more occurrences."
+
can also be written as {1,}
.
*
can also be written as {0,}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With