aanders77
aanders77

Reputation: 630

Regex for matching specific numbers separated by comma

I have a regex which matches any combination of the number 1,7 and 99, separated by commas. E.g. these should be matched:

1
1,7
1,99
99,1,7

While these should not match:

1,
8
8,99
,7
1,7,99,

The following works fine, but can probably be shortened and made more efficient?

/^(1|7|99)(,?(1|7|99)(,?(1|7|99))?)?$/

Upvotes: 2

Views: 140

Answers (3)

hemanth
hemanth

Reputation: 1043

Modifying @RidesTheShortBus's answer little bit works perfectly for all test cases

^(1|7|99)(,(1|7|99){1})*$

Tests here

Upvotes: 0

RidesTheShortBus
RidesTheShortBus

Reputation: 51

/^(1|7|99)(,(1|7|99))*$/

tested using your test cases on rubular

Upvotes: 1

anubhava
anubhava

Reputation: 786291

You can use lookahead based regex:

/^(1|7|99)(?!.*?,\1)(?:,(?:1|7|99))*$/gm

RegEx Demo

Upvotes: 2

Related Questions