1

I have this regex to match a repeating pattern:

/([0-9]{1,2}:[0-9]{1,2};)+/

It'll match strings like: 9:9; (1 set of numbers) or 12:2;4:9; (2 sets of numbers) or 5:2;7:7;5:2; (3 sets of numbers), and so on.

So far so good, but I need the semi-colon to be required to separate each set, while optional if it's at the end of the line. So I need it to accept both this: 5:2;7:7;5:2; and this: 5:2;7:7;5:2. This: 9:9; and this: 9:9.

How might this be achieved?

Works for a Living
  • 1,262
  • 2
  • 19
  • 44
  • I know you asked for Regex, but you tagged this as PHP as well. Why not just `$numbers = explode(';', $setOfNumbers);` – haz Aug 09 '16 at 22:41

2 Answers2

1

You can use (;|$) so the ending ; is optional

/([0-9]{1,2}:[0-9]{1,2}(;|$))+/

To avoid capturing ; you can use (?:;|$).
?: is a non-capturing group

Community
  • 1
  • 1
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
1

You could go for:

^(\d{1,2}:\d{1,2};?)+$

See a demo on regex101.com.
\d matches 0-9, ;? matches a semicolon if it is there , ^ and $ are anchors for a line.

Jan
  • 42,290
  • 8
  • 54
  • 79