I need to write a regex which matches strings representing comma separated days of week, like:
"Sun,Mon,Tue,Wed,Thu,Fri,Sat"
Each day can appear in the string at most once. The order of days is important.
So far I have tried the following patterns:
1) (Sun,|Mon,|Tue,|Wed,|Thu,|Fri,|Sat,)*(Sun|Mon|Tue|Wed|Thu|Fri|Sat)
This one is very bad: allows multiple presence of days, also doesn’t watch over the days order.
2) (Sun)?([,^]Mon)?([,^]Tue)?([,^]Wed)?([,^]Thu)?([,^]Fri)?([,^]Sat)?
This is the best I got so far. The only problem here is that it matches strings starting with comma, e.g. ,Mon,Tue,Fri. My question is how to filter out the comma starting string matching this pattern.
Thanks in advance.
Agreed that regex is possibly not the best option. However, if the only problem with your current version is that it matches strings beginning with a comma, you could just bung a check for a starting comma at the beginning of the regex:
However, I don’t think
[,^]does what you think it does – in the regex flavours I’m familiar with,^inside square brackets matches a literal^when it’s not the first character in the list – it doesn’t match the beginning of the string. You could replace it with(^|,):