Hagbart Celine
Hagbart Celine

Reputation: 470

Repeating pattern matching with Regex

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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:

  • If only single-digit numbers should be matched, use ^\d(?:,\d)?(?:;\d(?:,\d)?)*$
  • If the comma-separated number pairs can have the second element empty, add ? 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

Related Questions