Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate page numbers/ranges for printing

Tags:

java

regex

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!

like image 700
pankti Avatar asked Dec 20 '22 11:12

pankti


1 Answers

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
  • $: End
like image 137
anubhava Avatar answered Dec 31 '22 11:12

anubhava