I am writing a regular expression for matching a particular pattern which is as follows.
We all are familiar with the pattern that we give while printing selective pages via a word document. i.e.
Valid values:
1, 3, 6-9
1-5, 5
6, 9
Invalid values:
,5
5-,9
9-5,
2,6-
I have been using the pattern (([0-9]+)|(\\d.*[-,]\\d.*)+)
but it does not work for all permutation combination.
Any help would be greatly appreciated!
You may use this regex in Java:
^\d+(?:-\d+)?(?:,\h*\d+(?:-\d+)?)*$
RegEx Demo
RegEx Details:
^
: Start\d+(?:-\d+)?
: Match 1+ digits optionally followed by hyphen and 1+ digits(?:
: Start non-capture group
,
: Match a comma\h*
: Match 0 or more whitespaces\d+(?:-\d+)?
: Match 1+ digits optionally followed by hyphen and 1+ digits)*
: End non-capture group. *
repeats this group 0 or more times$
: EndIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With