Gerald
Gerald

Reputation: 1083

Regular expression to accept negative number

I have this regular expression below:

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

This will validate the input from a user to accept positive or negative numbers only that is comma separated or dash.

123,123,10
10,10
25
-25,10

My regular expression above is only working for positive numbers and comma separator. How can I modify this to work with dash (10-25-30) and negative numbers?

Upvotes: 2

Views: 6506

Answers (2)

anubhava
anubhava

Reputation: 784958

You can use this regex:

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

RegEx Demo

RegEx Details:

  • ^: Start
  • (: Start capture group
    • [-+]?: Optionally match - or +
    • [0-9]+: Match 1+ of any digit
    • [-,]: Match - or ,
  • )*: End capture group. * lets this group repeat 0 or more times
  • [+-]?: Optionally match - or +
  • [0-9]+: Match 1+ of any digit
  • $: End

Upvotes: 2

Toto
Toto

Reputation: 91375

Just add a minus sign before and make it optional:

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

Upvotes: 5

Related Questions