49

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
Griff
  • 1,647
  • 2
  • 17
  • 27

5 Answers5

99

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

Sergio Carneiro
  • 3,726
  • 4
  • 35
  • 51
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
50

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
Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • 1
    For those wishing to use this in a `grep` or `git grep` context, you'll need the `-E` option (a.k.a. `--extended-regexp`) for the `{n}` quantifier to be understood. – Quintin Willison May 14 '19 at 11:56
10

This should do the work:

^([0-9]*[a-zA-Z]){3,}[0-9]*$

It checks for at least 3 "Zero-or-more numerics + 1 Alpha" sequences + Zero-or-more numerics.

Marchev
  • 1,340
  • 1
  • 10
  • 11
0

You want to match zero or more digits then 3 consecutive letters then any other number of digits?

/\d*(?:[a-zA-Z]){3,}\d*/

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0

This is vanilla JS you guys can use. My problem is solved using this.

const str = "abcdggfhf";
const pattern = "fhf";

if(pattern.length>2) {
console.log(str.search(pattern));
}

Afridi
  • 1
  • 3