Reputation: 3150
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
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
Reputation: 726489
Try this expression:
[0-9][0-9,-]*-[0-9,-]*[0-9]
What this means is that the string must:
[0-9,-]
characters[0-9,-]
charactersUpvotes: 9
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