1
Valid1: 2

valid2: 3-5

Valid3: 2,4-6

valid4: 2,4,5

valid5: 2-7,8-9

Valid4: 2,5-7,9-13,15,17-20

All the expression on the above should be valid in one regex. the digit in the left side of hyphen should be smaller than right hand side.

5
  • What have you tried so far? No one is going to give you a full answer unless you show what you have tried and where you are stuck. Commented Oct 28, 2013 at 17:06
  • 6
    Regular expressions have no concept of the size of a number. You will need more than a regex to solve this problem. Commented Oct 28, 2013 at 17:06
  • for regexp you will need to use the following symbols : + , ( ) \d - you will also need to validate the numbers themselves though because you cannot compare numbers with regexp Commented Oct 28, 2013 at 17:10
  • i would recommend making your own finite state machine Commented Oct 28, 2013 at 17:11
  • possible duplicate of Trying to build a regular expression to check pattern Commented Oct 28, 2013 at 17:28

1 Answer 1

1

First, as @MikeFHay suggested above, regex were not made to check if one digit is bigger than the other (for that you'll have to parse the expression). If we'll ignore that requirement - the rest can be achieved via the following regex:

((\d\,(?=\d))|(\d\-(?=\d))|\d)+

in Java:

"((\\d\\,(?=\\d))|(\\d\\-(?=\\d))|\\d)+"

Explanation:
This regex uses lookahead to validate that each comma or dash is preceded and followed by a digit: (\d\,(?=\d)) so that each "substring" that contains a dash/comma will have to be in the format of: digit,digit or digit-digit.

Of course that a number that doesn't contain commas/dashes is also valid - hence the rightmost side of the or which is simply a \d

Link to online demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.