JavaScript regular expressions

I am not very new to regular expressions, but still have not been able to find an adequate expression for my problem:

I want to check a string that a user types in a text box. A string must consist of one or more members, separated by a semicolon.

There are actually two types of terms:

  • The first consists of a number followed by a hyphen, and then again a number, for example. 1-4or22-44

  • The second term consists of a number and a comma repeating zero or more times, for example. 1,2or4,5,6

All terms must be enclosed with a semicolon.

Valid input: 1-4;5,6,7;9-11;or1,3;4-6;8,9,10;

I tried so many variations, but have not yet found a solution. My problem is that this input string can consist of any number of members. I tried to solve this using the operator ORand "lookahead", respectively, but without success.

Any help would be greatly appreciated.

Thanks a lot, Enne

+5
source share
3 answers

This regex should do what you need:

/^(?:[0-9]+-[0-9]+;|[0-9]+(?:,[0-9]+)*;)+$/
+4
source

EDITED: first question: semicolons were delimiters, now they show them as terminators.

, , , :

/^(\d+(-\d+|(,\d+)*)?;)+$/

/^(?:\d+(?:-\d+|(?:,\d+)*)?;)+$/
+2

my welcome ..

^(?:\d+-\d+(?:;|$)|(?:\d+(?:[,;]|$))+)+$

+1
source

All Articles