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.
- We can use comma and hyphen
- no other special characters allowed
- should start and end with a number
- Comma and hyphen not allowed together, etc
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!
Advertisement
Answer
You may use this regex in Java:
^d+(?:-d+)?(?:,h*d+(?:-d+)?)*$
RegEx Details:
^
: Startd+(?:-d+)?
: Match 1+ digits optionally followed by hyphen and 1+ digits(?:
: Start non-capture group,
: Match a commah*
: Match 0 or more whitespacesd+(?:-d+)?
: Match 1+ digits optionally followed by hyphen and 1+ digits
)*
: End non-capture group.*
repeats this group 0 or more times$
: End