Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check for at least 3 characters?

Tags:

regex

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 
like image 371
Griff Avatar asked Mar 11 '13 14:03

Griff


People also ask

What does ?= * Mean in regex?

. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.

What does \+ mean in regex?

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.

What is difference [] and () in regex?

[] 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 .

How do I find a character in a string in regex?

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.


2 Answers

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 
like image 39
slackwing Avatar answered Sep 18 '22 12:09

slackwing


+ 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,}.

like image 60
Andy Lester Avatar answered Sep 22 '22 12:09

Andy Lester