FredLoh
FredLoh

Reputation: 1842

Using regex to find a character a certain number of times anywhere in a string

I'm generating all possible permutations of a string 10 characters long with the numbers 1, 2, 3.

I now want to check to see how many of the strings have the number 1 three times, 2 two times and 3 five times.

What is the correct regex for this if I am using egrep?

Upvotes: 0

Views: 207

Answers (2)

ndnenkov
ndnenkov

Reputation: 36100

You can use positive lookaheads:

(?=(.*1){3})(?=(.*2){2})(?=(.*3){5})^.{10}$

See it in action

However, note that this is not the perfect task to solve with regexes.


EDIT: Since you said you are using egrep, you can use piping instead:

echo 3121233133 | egrep '(.*1){3}' | egrep '(.*2){2}'| egrep '(.*3){5}' | egrep '^.{10}$'

Upvotes: 3

Tomalak
Tomalak

Reputation: 338228

This would be faster than regex:

input.replace("1", "").length === input.length - 3 &&
input.replace("2", "").length === input.length - 2 &&
input.replace("3", "").length === input.length - 5;

Upvotes: 1

Related Questions