c# - Repeating pattern matching with Regex -


i trying validate input regular expression. until tests fail , experience regex limited thought might able me out.

pattern: digit (possibly "," digit) (possibly ;)

a string may not begin ; , not end ;. digits allowed stand alone or

my regex (not working): ((\d)(,\d)?)(;?) problem not seem check until end of string. optional parts giving me headaches.

update: ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$this seems work better not match 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;

your ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$ regex matches 1 or more digits, optional sequence of , , 1 digit, followed one or more similar sequences.

you need match zero or more comma-separated numbers:

^\d+(?:,\d+)?(?:;\d+(?:,\d+)?)*$                               ^ 

see regex demo

now, tweaking part:

  • if single-digit numbers should matched, use ^\d(?:,\d)?(?:;\d(?:,\d)?)*$
  • if comma-separated number pairs can have second element empty, add ? after each ,\d (if single digit numbers matched) or * (if numbers can have more 1 digit): ^\d(?:,\d?)?(?:;\d(?:,\d?)?)*$ or ^\d+(?:,\d*)?(?:;\d+(?:,\d*)?)*$.

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -