0

I am trying to build a regex that will match the following comma separated value:

Pattern: A,A,A
Where A contains only digits or digits separated by "|" 
e.g. A = 111 or A = 111|222

The valid string could be

111,222|333,444
or
111|222,333,444

And the regex I have

^[[,]?[[\d]*|[\d]*\|[\d]*]]*$

However, when I test it, it returned true for the following patterns

111,222|333,
111,222,333|
,111,222,333|444
|111,222|333,444

How could I modify my regex to return false for those strings starting with "|" or "," and ended with "|" or ","

user3422290
  • 253
  • 5
  • 18

1 Answers1

2

You might use a repeating pattern with an optional group to match the | and 1 or more digits:

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

That would match

  • ^ Start of string
  • (?: Non capturing group
    • \d+ Match 1+ digits
    • (?:\|\d+)?, Optionally match | and 1+ digits followed by a ,
  • )+ Close non capturing group and repeat 1+ times (or * to repeat 0+ times)
  • \d+(?:\|\d+)? match 1+ digits and optionally match | and 1+ digits
  • $ End of string

Regex demo

Note that you can omit the brackets around \d and the comma.


If there can be multiple |, you can use the pattern suggested by ctwheels:

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

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70