Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to build a regular expression to check pattern

Tags:

regex

a) Start and end with a number
b) Hyphen should start and end with a number
c) Comma should start and end with a number
d) Range of number should be from 1-31

[Edit: Need this rule in the regex, thanks Ed-Heal!]
e) 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.
a) 1-5,5,15-29
b) 1,28,1-31,15
c) 15,25,3 [Edit: Replaced 56 with 3, thanks for pointing it out Brian!]
d) 1-24,5-6,2-9

Tried this but it passes even if the string starts with a comma:

/^[0-9]*(?:-[0-9]+)*(?:,[0-9]+)*$/
like image 881
webdev Avatar asked Mar 19 '26 18:03

webdev


1 Answers

How about this? This will check rules a, b and c, at least, but does not check rule d.

/^[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*$/

If you need to ensure that all the numbers are in the range 1-31, then the expression will get a whole lot uglier:

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

Note that your example c contains a number, 56, that does not fall within the range 1-31, so it will not pass the second expression.

like image 166
Brian Rogers Avatar answered Mar 22 '26 08:03

Brian Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!