Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript-Regular Expressions

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:

  1. The first consists of a number, followed by a hyphen and then followed by a number again, e.g. 1-4 or 22-44

  2. 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

like image 369
enne87 Avatar asked Jul 11 '11 01:07

enne87


2 Answers

This regex should do what you need:

/^(?:[0-9]+-[0-9]+;|[0-9]+(?:,[0-9]+)*;)+$/
like image 154
EdoDodo Avatar answered Sep 20 '22 07:09

EdoDodo


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+)*)?;)+$/
like image 44
Ray Toal Avatar answered Sep 19 '22 07:09

Ray Toal