FirmView
FirmView

Reputation: 3150

Regex matching hyphen and comma and only in between

I am checking for a string using regex.

The rule is :

The String can,

contain any digits, hyphen and comma

Hyphen and Comma should be only in-between the digits. It should not in the beginning or the end of the string.

Comma is optional. Hyphen is compulsory

For Example,

Valid :

10-20
10-20-3
10-20,3 

InValid :

10
-10
,10
10-20,
10-20-
10,20

The code I tried so far:

[0-9,-]+ 

can someone suggest how to check the coma and hyphen should not be in the beginning or end of the string and also the above conditions?

Upvotes: 3

Views: 12264

Answers (3)

vusan
vusan

Reputation: 5331

The expression should include ^ or \A at the beginning and $ or \z at end otherwise the expression would also match the invalid string like:

,10
20-
-34

So the expression should be :

^[0-9][0-9,-]*-[0-9,-]*[0-9]$

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Try this expression:

[0-9][0-9,-]*-[0-9,-]*[0-9]

What this means is that the string must:

  • Starts and ends in a digit
  • Contains at least one dash in the middle
  • after the first digit and before the dash there's zero or more [0-9,-] characters
  • between the dash and the last digit there's zero or more [0-9,-] characters

Upvotes: 9

John Corbett
John Corbett

Reputation: 1615

you should try this

[0-9][0-9,\-]*-[0-9,\-]*[0-9]

I think the hyphen needs to be backslashed in the character class

Upvotes: 1

Related Questions