【问题标题】:Regex an unordered list, separated by different 'delimiters' in python正则表达式一个无序列表,在 python 中由不同的“分隔符”分隔
【发布时间】:2015-01-30 23:57:42
【问题描述】:

我正在尝试构建一个正则表达式来捕获与\w{0,}?\s\d){0,} 匹配的字符串,即一个单词后跟空格,然后是一个数字。我已经模拟了here

仅用逗号分隔的前 N ​​个匹配项是组 1。
字符串“ opt ”之后的 N 个匹配项,仅用逗号分隔是第 2 组
字符串 ' 和/或 ' 之后的 N 个匹配项,仅用逗号分隔是第 3 组

我的尝试是这样的:((\w+?\s\d),\s+(\w+?\s\d))*(\s+and/or\s+(\w+?\s\d))*(\s+opt\s+(\w+?\s\d))*

Mind 3 opt Life 3, Prime 3 and/or Death 3 #This is not matched
Life 3, Mind 3 opt Prime 3 and/or Death 3 #This is matched
Life 3, Death 3 and/or Mind 3 opt Prime 3 #this is matched

但我确信存在我没有想到的极端情况。而且我从根本上知道这是与订单相关的,这是我不想要的。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    (?:|\s+and/or\s+|\s+opt\s+)((\w+?\s\d)(?:,\s+(\w+?\s\d))*)*

    您正在寻找三种不同的场景:

    String starts with nothingString starts with ' opt 'String starts with ' and/or '

    这与:

    (?:                     # Non matching group
        |                   # Nothing or 
        \s+and/or\s+|       # ' and/or ' or
        \s+opt\s+           # ' opt '
    )                       # followed by
    

    然后在每种情况下,您都在寻找一组或多组(\w+?\s\d),用逗号分隔。

    (
        (\w+?\s\d)          # a word followed by a single digit
        (?:,\s+             # preceeding comma and at least one space.
            (\w+?\s\d))*    # zero or more word-digit combinations as above,
    )*                      # Any number of these
    

    上面link的解释要好很多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      相关资源
      最近更新 更多