0

Let's say I need to have minimum 5 letters in a string not requiring that they are subsequent. The regex below checks subsequent letters

[A-Za-z]{5,}

So, "aaaaa" -- true, but "aaa1aa" -- false.

What is the regex to leave the sequence condition, that both of the strings above would pass as true.

2
  • Maybe [A-Za-z0-9]{5,} would be enough Commented Jun 11, 2018 at 6:50
  • Clarification: aaa1a should not pass! Commented Jun 11, 2018 at 7:19

5 Answers 5

4

You could remove all non-letter chars with .replace(/[^A-Za-z]+/g, '') and then run the regex:

var strs = ["aaaaa", "aaa1aa"];
var val_rx = /[a-zA-Z]{5,}/;
for (var s of strs) { 
  console.log( val_rx.test(s.replace(/[^A-Za-z]+/g, '')) );
}

Else, you may also use a one step solution like

var strs = ["aaaaa", "aaa1aa"];
var val_rx = /(?:[^a-zA-Z]*[a-zA-Z]){5,}/;
for (var s of strs) { 
  console.log( s, "=>", val_rx.test(s) );
}

See this second regex demo online. (?:[^a-zA-Z]*[a-zA-Z]){5,} matches 5 or more consecutive occurrences of 0 or more non-letter chars ([^a-zA-Z]*) followed with a letter char.

Sign up to request clarification or add additional context in comments.

Comments

1

Allow non-letter characters between the letters:

(?:[A-Za-z][^A-Za-z]*){5,}

Comments

1

If you have to use a regular expression only, here's one somewhat ugly option:

const check = str => /^(.*[A-Za-z].*){5}/.test(str);
console.log(check("aaaaa"));
console.log(check("aa1aaa"));
console.log(check("aa1aa"));

Comments

1

w means alphanumeric in regex, it will be ok : \w{5,}

Comments

0
[a-zA-Z0-9]{5,}

Just like this? Or do you mean it needs to be a regex that ignores digits? Because the above would match aaaa1 as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.