Home > Software design >  Regex matches specific number in capturing group
Regex matches specific number in capturing group

Time:03-09

I would like to understand how I can implement a Regex that matches a specific number in a capturing group which may be followed by a comma or be the absolute number.

I have built this Regex:

(0) (\*|16) (\*) (\*) (\*|1|(,[1]))

This Regex matches some patterns which aren't valid since I want to make sure I have any number 1 on the fifth group of the string.

Examples:

0 16 * * 4,6,1 # Valid 
0 16 * * 4,1,6 # Valid
0 * * * 3,1    # Valid
0 16 * * 6     # Invalid
0 * * * *      # Valid
0 16 * * 1,3,6 # Valid
0 16 * * 1     # Valid
0 16 * * 11    # Invalid 

So far the ones matched are:

0 * * * *      # Correct
0 16 * * 1,3,6 # Correct
0 16 * * 1     # Correct
0 16 * * 11    # Wrong

Any way I can get around with this? Thanks!

CodePudding user response:

(0) (\*|16) (\*) (\*) (\*|1|.*,1|1,.*|.*,1,.*)$

if we focus on the last part, we have either:

\*
1
.*,1
1,.*
.*,1,.*

the $ at the end is important for the first 3 cases to prevent e.g. 11, *1

Hoping it's what you wanted ;)

  • Related