membersound
membersound

Reputation: 86855

How to validate dash-separated values using regex?

I have a string with digits and separators. The digits may either be separated by a comma or a hyphen. But there may never be two digits that are both separated by hyphens without a comma in between.

Example:

valid: 123,12,2,1-3,1,1-3,1

invalid: 123,12,2,1-3,1,1-3-5,1

I have a regex that almost works, except it does not detect those 1-3-5 invalid lines.

How can I improve the following?

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

Upvotes: 1

Views: 2764

Answers (3)

Pshemo
Pshemo

Reputation: 124275

You can add condition using look-around which will search for -digits- so your regex can look like:

^(?!.*-\\d+-)[0-9]+([,-][0-9]+)*$
 ^^^^^^^^^^^^-negative look-ahead, match will fail if there is any -digits- in your string

Upvotes: 1

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51420

Here's a solution:

^(?:\d+(?:-\d+)?(?:,|$))+$

Demo

Explanation: Match a number, optionally followed by a dash and another number, then match either a comma or the end of the string. And repeat.

Upvotes: 2

fge
fge

Reputation: 121810

You can decompose your input:

  • normal: one or more digits, optionally followed by a dash then one or more digits;
  • special: a comma.

The regex for the normal case can be written as \d+(?:-\d+)?; for the special case, this is simply ,.

Applying the normal* (special normal*)* pattern, and adding anchors and quantifiers, we have:

^\d+(?:-\d+)?(,\d+(?:-\d+)?)*$

Upvotes: 2

Related Questions