Reputation: 3333
I have a string:
10-02;34-05;
Elements like dd-dd can be repeated many times:
10-02;34-05;12-02;23-05;10-42;44-05
At the end of the string the symbol ;
can be optional but between elements dd-dd the symbol ;
should be mandatory.
I tried ti build regular expression /^([0-9]{2}-[0-9]{2}[;])+$/)
but it covers cases like 10-02;34-05;12-02;23-05;10-42;44-05
but not 10-02;34-05;12-02;23-05;10-42;44-05;
with the symbol ;
at the end.
How Do I have to build an regular expression to cover both of cases.
Thanks.
Upvotes: 2
Views: 561
Reputation: 425428
This is about as simply/briefly as you can express it:
^(\d\d-\d\d(;|$))+$
Upvotes: 2
Reputation: 14931
Simple ^(?:\d{2}-\d{2}(?:;|$))+$
Which means:
^ # start of line
(?: # non-capturing group
\d{2} # match 2 digits
- # match a hyphen
\d{2} # match 2 digits
(?:;|$) # match ; or end of line
)+ # repeat 1 or more times
$ # end of line
Note
10-02;34-05;12-012;23-05;10-42;44-05;
^--- You have 3 digits here ??? If so change all {2} to +
Upvotes: 3
Reputation: 622
Use something like this:
^(\d{2}-\d{2};)*\d{2}-\d{2}(;)?$
The ?
operator makes the last parenthized expression optional, like placing a {0, 1}
after it.
Upvotes: 1
Reputation: 32827
You can use ?
to optionally match a pattern
^\d{2}-\d{2}(;\d{2}-\d{2})*;?$
or
^(\d{2}-\d{2};)*(\d{2}-\d{2};?)$
Upvotes: 2