Names of days or the first 3 characters

I want my regex to catch:

monday mon thursday thu ...

So, you can write something like this:

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

But I think there should be a more elegant solution.

+3
source share
1 answer

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

?- this is a "zero repetition"; therefore, it looks like "optional."

If you do not need all suffix locks, you can use groups that are not exciting (?:___), so:

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

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

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

I am not sure if this is more readable.

References


Another option

Java Matcher , . Python , , (, , ) 3 , monday|tuesday|.... (.. ).

:

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!"
         );
      }
   }
}

( 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

+3

Source: https://habr.com/ru/post/1750539/


All Articles