How good is my regex

  • Thread starter Captain Paralytic
  • Start date
C

Captain Paralytic

I need to validate that a string meets the following criteria.

Is at least 1 digit > 0 (1-9)
May contain commas, hyphens and spaces
Must begin with a digit (1-9)
Must end with a digit (0-9)
Any new group of digits (either the first in the string or immediately
following a comma, space or hyphen) must begin with (1-9)

So:
good
1
123
1 456-567,676

bad
01
123,
,345
123 0456
123,345-087

I've come up with a couple of REGEXs but I'm no regexpert (geddit - I
know, no comedian either), but I'm sure there's a tidier way.
 
P

p.lepin

I need to validate that a string meets the following
criteria.

Is at least 1 digit > 0 (1-9)
May contain commas, hyphens and spaces
Must begin with a digit (1-9)
Must end with a digit (0-9)
Any new group of digits (either the first in the string
or immediately following a comma, space or hyphen) must
begin with (1-9)

/^[1-9]\d*([,\- ][1-9]\d*)*$/
 
C

Captain Paralytic

I need to validate that a string meets the following
criteria.
Is at least 1 digit > 0 (1-9)
May contain commas, hyphens and spaces
Must begin with a digit (1-9)
Must end with a digit (0-9)
Any new group of digits (either the first in the string
or immediately following a comma, space or hyphen) must
begin with (1-9)

/^[1-9]\d*([,\- ][1-9]\d*)*$/

Looks neater than mine (no surprise there - and I discovered that mine
didn't do all of the rules either!). I'll try it out tonight. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top