Jim Matthews Jim Matthews - 11 months ago 49
Linux Question

Coding a regex to return true for an EXACT count of a group

I'm using the regex below to return numbers that contain exactly 3 instances of the digits 6,7 and 8 (with 0 to many other digits between each). I know there has to be a way to match exactly 3 without matching more instances but I can't find it anywhere.

echo $num | egrep '(6.*|7.*|8.*){3}' | egrep -v '(6.*|7.*|8.*){4}' | egrep -v '(6.*|7.*|8.*){5}'`

I'm trying to match numbers like 4561863 but not 466773.

Answer Source

The trick is to first match any number of digits that aren't 6, 7, or 8, then match 3 groups of numbers that start with a 6, 7, or 8 followed by any number of not-6,7,8.

echo "$num" | grep -E '^[0-5,9]*([6-8][0-5,9]*){3}$'