开发者

Day names or first 3 characters

I want my regex to catch:

monday mon thursday thu ...

So it's possible to write something like this:

开发者_如何学JAVA
(?P<day>monday|mon|thursday|thu ...

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


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

  • regular-expressions.info/Repetition and Grouping

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

  • Can java.util.regex.Pattern do partial matches?
  • How can I perform a partial match with java.util.regex.*?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜