【问题标题】:Day names or first 3 characters日期名称或前 3 个字符
【发布时间】:2010-06-17 17:00:18
【问题描述】:

我希望我的正则表达式能够捕获:

monday mon thursday thu ...

所以可以这样写:

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

但我想应该有更优雅的解决方案。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    可以写mon(day)?|tue(sday)?|wed(nesday)?

    ? 是“零或一重复”;所以它有点“可选”。

    如果你不需要所有的后缀捕获,你可以使用(?:___)非捕获组,所以:

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

    如果愿意,您可以将周一/周五/周日组合在一起:

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

    不过,我不确定这是否更具可读性。

    参考文献


    另一种选择

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

    这打印(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
    

    相关问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 2014-11-16
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多