Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to build a regular expression to check pattern - 2

Tags:

regex

match

I was wondering if more checks could be added: [Previously answered question]( Trying to build a regular expression to check pattern).

The above problem is brilliantly solved using this regex by Brian Rogers:

/^([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]))?)*$/  

[For Reference, posting the older problem again]

  1. Start and end with a number
  2. Hyphen should start and end with a number
  3. Comma should start and end with a number
  4. Range of number should be from 1-31
  5. If a number starts with a hyphen (-), it cannot end with any other character other than a comma AND follow all rules listed above.

E.g. 2-2,1 OR 2,2-1 is valid while 1-1-1-1 is not valid.

E.g.:
- 1-5,5,15-29
- 1,28,1-31,15
- 15,25,3 - 1-24,5-6,2-9

Could this go a step further and add other validations?

1) The numbers should be in ascending order
E.g:
- 1,2-3 - Valid
- 4-6,23 - Valid
- 23,4-5 - Invalid

2) The numbers should not repeat
E.g:
a) 2,2,2 - Invalid
b) 2,3-6,3 - Invalid
c) 2,5,7-20 - Valid

3) If possible
Number should not repeat if previously defined in range
E.g:
a) 2,3-6, 4 - Invalid, because 4 is already a number between 3 and 6
b) 12-16, 14-18 - Invalid, because 14,15 and 16 are already defined in 12-16
c) 9-13, 15, 17-19 - Valid

like image 420
webdev Avatar asked Dec 22 '11 11:12

webdev


People also ask

How do you check a regular expression?

RegExp.prototype.test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or false . JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y ).

What is $2 regex?

$1 is the first group from your regular expression, $2 is the second. Groups are defined by brackets, so your first group ($1) is whatever is matched by (\d+). You'll need to do some reading up on regular expressions to understand what that matches.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .


1 Answers

Regular expression is supposed to check a pattern and not to handle business logic. The moment you start stating your problem with "if ... then ... else", it's not something regular expression is supposed to handle.

like image 117
Bipul Avatar answered Oct 20 '22 17:10

Bipul