Python正则表达式匹配可选的成对字符,如1st 2nd 1 2等

时间:2019-07-18 19:12:52

标签: python regex

我希望匹配以下字符串:1st,2nd,3rd和/或1、2、3,然后是Ro | ro | Cl | cl

我很难匹配可选对[st | nd | rd] / [ro | cl]。我该怎么办?

到目前为止,这是我所拥有的,但是它无法匹配成对的可选字符:

\d+\s*[st|nd|rd|th]?\s*[cl|ro]

请注意,示例字符串看起来像这样:

bob 1st router
ed 3rd Cleaner
6 cleaner bob
7 router fred

Regex101 Demo:

1 个答案:

答案 0 :(得分:2)

方括号指示集合中的任何单个字符都应匹配。 [ro|cl]与“ ro或cl”不匹配,与“ r或o或pipe或c或l”匹配。

请改用括号:

\d+\s*(st|nd|rd|th)?\s*(cl|ro)

Regex101 demo

import re

test_cases = [
    "bob cleaner",
    "bob 1st router",
    "2nd router",
    "ed 3rd Cleaner",
    "sam router",
    "4th Router",
    "5th Cleaner",
    "6cleaner bob ",
    "7 router sam",
    "8th Cleaner",
]

for s in test_cases:
    print(s)
    m = re.search(r"\d+\s*(st|nd|rd|th)?\s*(cl|ro)", s, re.IGNORECASE)
    if m:
        print("  " + m.group())
    else:
        print("  No match.")

结果:

bob cleaner
  No match.
bob 1st router
  1st ro
2nd router
  2nd ro
ed 3rd Cleaner
  3rd Cl
sam router
  No match.
4th Router
  4th Ro
5th Cleaner
  5th Cl
6cleaner bob
  6cl
7 router sam
  7 ro
8th Cleaner
  8th Cl