Home > OS >  Regular expression does not allow a dash
Regular expression does not allow a dash

Time:10-26

Currently using a text field and need some validation for capturing days of a month.

^(?:[1-9]|[12][0-9]|3[01])(?:(?: *- *(?:[1-9]|[12][0-9]|3[01]))?(?: *, *(?:[1-9]|[12][0-9]|3[01])(?: *- *(?:[1-9]|[12][0-9]|3[01]))?) )?$

My regular expression will allow a value like 1-30, 27, 3, 13.

But not 10-27.

Any suggestions on getting both examples to evaluate correctly?

Tried searching for examples allowing a dash by adding - but received the same result.

CodePudding user response:

You can use

^  # start of string
 (?:[1-9]|[12][0-9]|3[01])  # a day pattern
 (?:            # start of an optional non-capturing group
    \ *-\ *     # a hyphen enclosed with zero or more spaces
    (?:[1-9]|[12][0-9]|3[01]) # a day pattern
 )?             # end of the optional group
 (?:            # start of an optional non-capturing group
   \ *,\ *(?:[1-9]|[12][0-9]|3[01]) # comma inside optional spaces   day pattern
   (?:\ *-\ *(?:[1-9]|[12][0-9]|3[01]))? # an optional sequence of hyphen inside optional spaces   day pattern
 )* # repeat zero or more times
$  # end of string

See the regex demo.

A one liner:

^(?:[1-9]|[12][0-9]|3[01])(?: *- *(?:[1-9]|[12][0-9]|3[01]))?(?: *, *(?:[1-9]|[12][0-9]|3[01])(?: *- *(?:[1-9]|[12][0-9]|3[01]))?)*$

See this demo.

  • Related