user1546193
user1546193

Reputation: 53

regex to match number comma number

This is what I have right now:

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

My problem is that i want to be able add more than one digit before and after my comma.

examples:

1,12
12,12
123,12
12,123

All above numbers are supposed to be valid.

Upvotes: 3

Views: 10263

Answers (3)

David Rodrigues
David Rodrigues

Reputation: 12532

You have two regex main repeaters, the first is *, that say "repeat zero or more times". The second is + that say "repeat one or more time".

In this case, you need repeat one or more times the integer value and the decimal value. So you can try it:

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

So it will validate:

  0
  0123
  1,12
  1,0
  1,12340

But not will validate:

  1,
  ,0
  -1,0
  1e-10

Tips:

  • You can replace [0-9] with only \d. It mean the same thing;
  • You don't need group comma, just use , instead of [,]. You use that only for more than one possibilities, like accept comma and dot: [,\.];

Following the tips, you can try:

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

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

I'd suggest the following:

/^\d+,\d+$/

The + 'matches the preceding item one or more times.'

References:

Upvotes: 9

Engineer
Engineer

Reputation: 48793

Use + sign, and also remove [] brackets around ,(they are not neccessary):

^[0-9]+(,[0-9]+)?$
  //  ^-------^---------here they are

Upvotes: 4

Related Questions