Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match at least one from set of characters in specific order

Tags:

regex

I have a string which contains a sub-string of days. This sub-string contains a single character representing each applicable weekday and can contain any combination of weekdays, or the letter N where no weekday applies. Each weekday is represented by the first character, except Thursday which is an R, and weekdays must be in order.

I've tried to build a regular expression to match this substring but the regex I have written is matching blank strings.

My Regex is: ^ABC ((M?T?W?R?F?)|N) ABC$

I want this to match:

  • ABC M ABC
  • ABC MWR ABC
  • ABC TRF ABC
  • ABC N ABC

etc...

But not match:

  • ABC Z ABC
  • ABC TRM ABC

The regex is doing this, but is also matching:

  • ABC ABC

Does anyone have a quick fix?

Edit: I forgot to mention that due to limitations of the host environment I'm restricted to using the Microsoft VBScript Regular Expressions 5.5 library and it's subset.

like image 403
Irwell Avatar asked Sep 07 '25 20:09

Irwell


1 Answers

You can use lookahead regex:

^ABC (?=\S)(M?T?W?R?F?|N) ABC$
  • (?=\S) is to make sure next character is not space.

RegEx Demo

like image 192
anubhava Avatar answered Sep 10 '25 11:09

anubhava