3

I want my regex to catch:

monday mon thursday thu ...

So it's possible to write something like this:

(?P<day>monday|mon|thursday|thu ...

But I guess that there should be a more elegant solution.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
pocoa
  • 4,197
  • 9
  • 37
  • 45

1 Answers1

3

You can write mon(day)?|tue(sday)?|wed(nesday)?, etc.

The ? is "zero-or-one repetition of"; so it's sort of "optional".

If you don't need all the suffix captures, you can use the (?:___) non-capturing groups, so:

mon(?:day)?|tue(?:sday)?|wed(?:nesday)?

You can group Monday/Friday/Sunday together if you wish:

(?:mon|fri|sun)(?:day)?

I'm not sure if that's more readable, though.

References


Another option

Java's Matcher lets you test if there's a partial match. If Python does too, then you can use that and see if at least (or perhaps exactly) 3 characters matched on monday|tuesday|.... (i.e. all complete names).

Here's an example:

import java.util.regex.*;
public class PartialMatch {
   public static void main(String[] args) {
      String[] tests = {
         "sunday", "sundae", "su", "mon", "mondayyyy", "frida"
      };
      Pattern p = Pattern.compile("(?:sun|mon|tues|wednes|thurs|fri|satur)day");
      for (String test : tests) {
         Matcher m = p.matcher(test);
         System.out.printf("%s = %s%n", test, 
            m.matches() ? "Exact match!" :
            m.hitEnd() ? "Partial match of " + test.length():
            "No match!"
         );
      }
   }
}

This prints (as seen on ideone.com):

sunday = Exact match!
sundae = No match!
su = Partial match of 2
mon = Partial match of 3
mondayyyy = No match!
frida = Partial match of 5

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623