Thom Thom - 3 months ago 9
PHP Question

Make required character in repeating pattern optional only at the end of the string

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?

Answer

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