I'm not very new with regular expressions, but I haven't been able to find an adequate expression for my problem so far:
I want to check a string that a user types into a textfield. The string has to consist of one ore more terms that are separated with a semicolon.
There are actually two types of terms:
The first consists of a number, followed by a hyphen and then followed by a number again, e.g. 1-4
or 22-44
The second term consists of a number and a comma repeated zero or more times, e.g. 1,2
or 4,5,6
All terms have to be concluded with a semicolon.
A valid input would be: 1-4;5,6,7;9-11;
or 1,3;4-6;8,9,10;
I've tried so many variations but couldn't find a solution so far. My problem is that this input string may consists of any number of terms. I tried to solve this with the OR
operator and "lookahead", respectively, but with no success.
Any help would be very appreciated.
Thanks much, enne
This regex should do what you need:
/^(?:[0-9]+-[0-9]+;|[0-9]+(?:,[0-9]+)*;)+$/
EDITED: The first question looked the semicolons were separators, now it shows them as terminators.
Here is a sequence of one or more terms, terminated by semicolons, in which each term is either a number or a number range or a list of comma-separated numbers:
/^(\d+(-\d+|(,\d+)*)?;)+$/
With non-capturing groups
/^(?:\d+(?:-\d+|(?:,\d+)*)?;)+$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With