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]
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
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 ).
$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.
\\. 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?\ ' .
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.
If 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