FirmView
FirmView

Reputation: 3150

Regex checking for Numbers and Alphabets

I am trying to match strings which contain only having numbers with comma and numbers with hyphens like,

Should match,

   22-10,3,34-2,16
   22,10,3,34,2,16
   22-10-3-34-2-16
   23-10,6

Should not match,

   4ABS-NTts
   ABS,NT
   2

Any help would be very helpful

Upvotes: 2

Views: 444

Answers (2)

Dariush Jafari
Dariush Jafari

Reputation: 5443

Try this:

^(?:\d+[,-]?)+\d+$

it matches bare numbers like 23 too.
You can test it in this site.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

Try this:

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

Explanation:

^         # Start of string
(?:       # Try to match:
 [0-9]+   #  one or more digits
 [,-]     #  one separator (- or ,)
)+        # once or more.
[0-9]+    # Match one or more digits
$         # End of string

Upvotes: 3

Related Questions