Say I am given a string (555)-555-5555, is there a way to check if the string contains exactly 10 occurrences of the number 5? I can think of other ways to solve this, but I am curious if this can be done with a regEx. I tried using
var re = new regExp(/5{10}/);
but apparently this only matches ten 5's in a row.
Asked
Active
Viewed 63 times
0

RoryAvant
- 49
- 5
-
1This is not a duplicate... – Galik May 12 '16 at 02:31
-
Try: `^(?:[^5]*5){10}[^5]*$` – Galik May 12 '16 at 02:37
-
Definitely not a duplicate. – RoryAvant May 12 '16 at 03:07
2 Answers
3
1) Delete all non-5
, count the remains.
str.replace(/[^5]/g, '').length == 10
2) Count 5
-with-a-tail groups:
str.match(/^[^5]*(?:5[^5]*){10}$/)
EDIT: fixed bugs. Also, the explanation: the entirety of the string (^...$
) consists of any number of non-5
, followed by exactly 10 groups of one 5
and any number of non-5
. Thus,
x55pp5peep5o5555taco5lol5
breaks down into
^ start of string
[^5]* x
(?:5[^5]*){10} 5
5pp
5peep
5o
5
5
5
5taco
5lol
5
$ end of string

Amadan
- 191,408
- 23
- 240
- 301
-
Nice, I like the first solution, having a little trouble understanding the second solution though, I'm still a noob with regEx's. – RoryAvant May 12 '16 at 02:59
0
A "mostly" regex solution would be to match replace all other characters with the empty string and check the length of your result. Or similarly you could match and replace the character you want with the empty string and take the difference and see if it's the number you want.

winhowes
- 7,845
- 5
- 28
- 39