Allan
Allan

Reputation: 1272

Simplify a repeating regex pattern

I have some numeric identifiers with a simple, but repeating pattern, that I am searching for within a document. For example, one particular string has five, four digit numbers and a two digit number each separated by a space:

1234 1234 1234 1234 1234 12

I created a regex pattern (used in egrep) that is formatted as follows:

 [0-9]{4}[[:blank:]][0-9]{4}[[:blank:]][0-9]{4}[[:blank:]][0-9]{4}[[:blank:]][0-9]{4}[[:blank:]][0-9]{2}

This works. However, I'm trying to find out if there's a way simplify this. For example, I want to write a regex that says I have five patterns of [0-9]{4}[[:blank:]].

How can I simplify/shorten this regex pattern?

Upvotes: 0

Views: 235

Answers (1)

Peter Thoeny
Peter Thoeny

Reputation: 7616

You can group any pattern (), and specify the number of repetitions {n}. Here is your example trying with 5 and 6 repetitions:

$ echo '1234 1234 1234 1234 1234 12' | egrep '([0-9]{4}[[:blank:]]){5}'
1234 1234 1234 1234 1234 12
$ echo '1234 1234 1234 1234 1234 12' | egrep '([0-9]{4}[[:blank:]]){6}'
$

Upvotes: 2

Related Questions