Frage

I'm trying to write a JavaScript regular expression to only allow the following inputs:

  • Numbers
  • Numbers with commas in between
  • Numbers with hyphens in between, but only followed by another number or a comma, followed by a number. This pattern can repeat again.

So far, I have the following expression:

^[0-9]$|^[0-9]+$|^[0-9](-?,?[0-9])*$

However, this is allowing 1-1-1, which I do not want. A hyphen can only appear if not followed by another number-hyphen-number combo.

This link might help: http://regexr.com?34ljt

The following samples should evaluate as being valid:

01,03,05-08,10
01,03,05
01,03,05-08
01
1,1,5-6,1,1
1,1,5-6,1,1-3
12,12,1-9
1-9,5,5
1-9,9,9,5-6
1-2
11-11
11,11
1,1
1,1,1
11,11,11
1111
1,1,1,1,1,1
1
56,1
1,1
1,3
1,3,4,5
1,3

The following samples should evaluate as being invalid:

sdfdf
11-11-11-11
1-1-1-1-1
f
01,
01,03,05-08,
-1,4-,-5,8909
1,1,1-1-1
1,1,11-1111-1
1-1-1
1,,1
1--1
1-
1,,
,-1-
df
-1
,1

War es hilfreich?

Lösung 2

Try

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

Further to the comments

One way to prevent a match if there are consecutive ranges is to add a negative look-ahead

(?!.*-\d+,\d+-)

so the regex becomes

/^(?!.*-\d+,\d+-)\d+(-\d+)?(,\d+(-\d+)?)*$/

If the pattern inside the negative look-ahead can be matched it prevents the whole regular expression from matching. The .* is used so that if e.g. -1,1- is found anywhere ahead in the string, a match will be prevented.

Andere Tipps

Nice link, and kudos for giving enough examples to thoroughly determine whether a solution is correct. This seems to work:

^([0-9]+(-[0-9]+)?(,(?!$)|$))+$

http://regexr.com?34lk6

So: numbers, optionally followed by a dash and more numbers, followed by either a comma (unless the comma is the last character before the end of line) or end of line.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top