Could someone help me about to create a posix regex?

160 Views Asked by At

could someone help me to create a posix regex which checks if the entered string follows the following pattern:

Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

Or

Monday, Wednesday, Friday

Or

Sunday

Then:

  1. Days of the week followed by ", "
  2. I can't repeat a day of the week
  3. The last day of a string must not have ", "
1

There are 1 best solutions below

2
logi-kal On

If the order of days doesn't matter, use:

^((Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)(, (?!$)(?!.*\2)|$))*$

See demo here.

Explanation:

  • The inner parenthesis are used for expressing the disjunction of days.
  • ^ matches the begin of the string.
  • $ matches the end of the string.
  • (?!$) means that comma must not be follwed by the end of string.
  • (?!.*\2) means not followed by any number of characters (.*) and the second group (\2), that is the innermost one.

About the last point, I suggest you to google about regex matching groups, lookarounds backreferences