Reputation: 470
I am trying to validate an input with a regular expression. Up until now all my tests fail and as my experience with regex is limited I thought someone might be able to help me out.
Pattern: digit (possibly "," digit) (possibly ;)
A String may not begin with a ; and not end with a ;. Digits are allowed to stand alone or with
My regEx (not working): ((\d)(,\d)?)(;?)
the problem is it does not seem to check until the end of the string. Also the optional parts are giving me headaches.
Update: ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$
this seems to work better but it does not match the single digit.
OK:
2,3;4,4;3,2
2,3
2
2,3;3;4,3
NOK:
2,3,,,,
2,3asfafafa
;2,3
2,3;;3,4
2,3;3,4;
Upvotes: 1
Views: 387
Reputation: 627103
Your ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$
regex matches 1 or more digits, then an optional sequence of ,
and 1 digit, followed with one or more similar sequences.
You need to match zero or more comma-separated numbers:
^\d+(?:,\d+)?(?:;\d+(?:,\d+)?)*$
^
See the regex demo
Now, tweaking part:
^\d(?:,\d)?(?:;\d(?:,\d)?)*$
?
after each ,\d
(if single digit numbers are to be matched) or *
(if the numbers can have more than one digit): ^\d(?:,\d?)?(?:;\d(?:,\d?)?)*$
or ^\d+(?:,\d*)?(?:;\d+(?:,\d*)?)*$
.Upvotes: 2