Chris
Chris

Reputation: 1019

regex for comma separated numbers in brackets

I am searching for regex which could be used for testing number or comma separated numbers in {} brackets

34
{567}
{12,13,14,30,101,23}

I have following regex which works find for first two examples but not no third one

echo "{2424242,243,243,2,2,11}"|grep -E '^([1-9][0-9]*|\{[1-9][0-9]*\}|\{([1-9][0-9]*,)[1-9][0-9]*\})$'

what is wrong with: \{([1-9][0-9]*,)[1-9][0-9]*\}?

Upvotes: 2

Views: 1568

Answers (3)

kyodev
kyodev

Reputation: 583

a=(34)
a+=( '{567}' )
a+=( '{12,13,14,30,101,23}' )

a+=( '{12,13,14,30,101,23' )
a+=( '12,13,14,30,101,23}' )
a+=( '12,13,14,30,101,23' )

regex='^([1-9][0-9]*|\{[1-9][0-9]*(,[1-9][0-9]*)*\})$'

for test in ${a[@]}; do
    grep -E "$regex" <<< "$test"
done

for test in ${a[@]}; do
    [[ $test =~ $regex ]] && echo ok : "$test"
done

output:

34
{567}
{12,13,14,30,101,23}
ok : 34
ok : {567}
ok : {12,13,14,30,101,23}

Upvotes: 0

revo
revo

Reputation: 48741

The wrong thing is that you don't look for repeated comma separated digits, you allow a single comma and restrict numbers to start with 1 through 9 (skip this if it is on purpose). I think you have to do this:

^([0-9]+|{[0-9]+(,[0-9]+)*})$

Upvotes: 1

Moti Korets
Moti Korets

Reputation: 3748

It is missing the last case when we don't have the comma at the end. And it doesn't account for repetition. So adding ? after the comma and + after the inner capturing group ([1-9][0-9]*,)+ solves the problem. This one matches the last line too:

^([1-9][0-9]*|\{[1-9][0-9]*\}|\{([1-9][0-9]*,?)+[1-9][0-9]*\})$

You can see the live version here
By the way it could be written in shorter way but i will leave it to you preference.

Upvotes: 1

Related Questions