5

I'm trying to test whether or not an unordered string has '3' in it 5 times.

For example:

var re = /3{5}/;
re.test("333334"); //returns true as expected
re.test("334333"); //returns false since there is no chain of 5 3s

What regex would make the second line return true? If regex is not the best way to test this, what is?

Thanks!

4 Answers 4

6

Try

(str.match(/3/g) || []).length >= 5

Or

str.split(3).length > 5

Where str is the string you want to test.

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

4 Comments

It should be str.split('3') (with the quotes). Fixed for you.
@SashaChedygov Quotes are not necessary. From ES5 spec Section 15.5.4.14, at step 8, "If separator is a RegExp object (its [[Class]] is "RegExp"), let R = separator; otherwise let R = ToString(separator)."
@Oriol: Thanks for the clarification, I didn't know that. I'd still prefer the quotes, but that's just me. :)
@SashaChedygov Also note that the split way needs > instead of >=, because it counts an additional item: ''.split(3).length === 1, '3'.split(3).length === 2, and so on.
3

You can write this:

var re = /(?:3[^3]*){5}/;

2 Comments

Hi, I'm new to regexp and am having trouble understanding capture parentheses. According the the MDN, this would match '3[^3]*' but not remember the match. What exactly does this mean?
@Ativ: yes (?:...) are non-capturing parenthesis. The goal is only to group, to be able to put the {5} quantifier in factor. A capturing group will store the content to be reuse later (with a backreference). But it is not needed here. Using non-capturing group use obviously less memory, and is a little faster.
2

I would go for

s.replace(/[^3]/,'').length >= 5

Assuming that the string to be tested is named s

Comments

0

I would go with:

string.indexOf('33333') > -1

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.