1

I have an input that I want to apply validation to. User can type any integer (positive or negative) numbers separated with a comma. I want to

Some examples of allowed inputs:

1,2,3
-1,2,-3
3
4
22,-33

Some examples of forbidden inputs:

1,,2
--1,2,3
-1,2,--3
asdas
[]\%$1

I know a little about regex, I tried lots of ways, they're not working very well see this inline regex checker:

^[-|\d][\d,][\d]
Emma
  • 27,428
  • 11
  • 44
  • 69
Ahmad Mobaraki
  • 7,426
  • 5
  • 48
  • 69

2 Answers2

4

You can use

^(?:-?[0-9]+(?:,(?!$)|$))+$

https://regex101.com/r/PAyar7/2

  • -? - Lead with optional -
  • [0-9]+ - Repeat digits
  • (?:,(?!$)|$)) - After the digits, match either a comma, or the end of the string. When matching a comma, make sure you're not at the end of the string with (?!$)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

As per your requirements I'd use something simple like

^-?\d+(?:,-?\d+)*$
  • at start ^ an optional minus -? followed by \d+ one or more digits.

  • followed by (?:,-?\d+)* a quantified non capturing group containing a comma, followed by an optional hyphen, followed by one or more digits until $ end.

See your updated demo at regex101


Another perhaps harder to understand one which might be a bit less efficient:

^(?:(?:\B-)?\d+,?)+\b$
  • The quantified non capturing group contains another optional non capturing group with a hyphen preceded by a non word boundary, followed by 1 or more digits, followed by optional comma.

  • \b the word boundary at the $ end ensures, that the string must end with a word character (which can only be a digit here).

You can test this one here at regex101

bobble bubble
  • 16,888
  • 3
  • 27
  • 46