Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression does not allow a dash

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions on getting both examples to evaluate correctly?

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading