Zesty
Zesty

Reputation: 2981

Need a regex that accepts any text that contains at least 3 alphabets

I need a regular expression that accepts any string that contains at least 3 English alphabets. The alphabets can be anywhere in the string.

Test cases:

Should return true for:

abc
This is a test
This number 123 just $@!!.
123ABC289389798

Should return false for:

ab
ab213823897

EDIT: Sorry, I should clarify that it needs 3 English alphabets. The alphabets can be anywhere in the string.

Upvotes: 1

Views: 301

Answers (5)

Lily
Lily

Reputation: 316

How about something like this?

[A-Za-z].*[A-Za-z].*[A-Za-z]

The [A-Za-z] matches any character from A-Z or from a-z. This regex guarantees that you have 3 of these characters. The .* matches any number of any character, so your three alpha characters can be consecutive or have anything before/after/in between.

Test it out at a regex tool like http://gskinner.com/RegExr/

You can also consolidate it like this:

([A-Za-z].*){3}

EDIT: replaced \w with [A-Za-z] and added explanation.

EDIT2: thanks @nhahtdh, removed .* from beginning and end since we only need a match, not coverage of the whole string.

Upvotes: 7

Julien Grenier
Julien Grenier

Reputation: 3394

Here's one solution:

string.replace(/[\W^\d]/g, '').length >= 3;

Upvotes: 0

CuriousMind
CuriousMind

Reputation: 34135

This will work:

[a-zA-Z]{3,}

it will match, 3 or more of a-z & A-Z chars

Upvotes: 1

Broxzier
Broxzier

Reputation: 2949

If you want all letters to return true back to back, simply use:

[a-zA-Z]{3,}

This doesn't include spaces.

If you do not need to place these back to back, try this:

[a-zA-Z].*?[a-zA-Z].*?[a-zA-Z]

Upvotes: 3

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

or perhaps :

/([a-z]|[A-Z]){3,}/

http://jsbin.com/oleseb/1/edit

Upvotes: 1

Related Questions