首页 > 解决方案 > 使用 python re 需要匹配以两种可能模式开始和结束的字符串

问题描述

该| 正则表达式中的符号似乎划分了整个模式,但我需要划分一个较小的模式......我希望它找到一个以“Q:”或“A:”开头的匹配,然后在下一个之前结束“问:”或“答:”。中间可以是任何东西,包括换行符。

我的尝试:

string = "Q: This is a question. \nQ: This is a 2nd question \non two lines. \n\nA: This is an answer. \nA: This is a 2nd answer \non two lines.\nQ: Here's another question. \nA: And another answer."

pattern = re.compile("(A: |Q: )[\w\W]*(A: |Q: |$)")

matches = pattern.finditer(string)
for match in matches:
    print('-', match.group(0))

我使用的正则表达式是(A: |Q: )[\w\W]*(A: |Q: |$).

这是多行的相同字符串,仅供参考:

Q: This is a question. 
Q: This is a 2nd question 
on two lines. 

A: This is an answer. 
A: This is a 2nd answer 
on two lines.
Q: Here's another question. 
A: And another answer.

所以我希望括号能将开头的两种可能模式和结尾的三种模式隔离开来,但它却将其视为 4 个单独的模式。它还会在末尾包含下一个 A: 或 Q:,但希望你能看到我的意图。我正打算不使用那个组或其他东西。

如果有帮助,这是一个简单的学习程序,它从文本文件中获取问题和答案以对用户进行测验。我能够通过每个只有一行的问题和答案来做到这一点,但是我无法获得包含多行的“A:”或“Q:”。

标签: pythonregexre

解决方案


我建议为此使用 for 循环,因为至少对我来说更容易。要回答您的问题,为什么不只针对期间而不是下一个 A: | 问:?否则你可能不得不使用前瞻。

(A: |Q: )[\s\S]*?\.

[\s\S](通常用于匹配每个字符,但[\w\W]也可以)

*?是一个惰性量词。它匹配尽可能少的字符。如果我们有 just (A: |Q: )[\s\S]*?,那么它只会匹配(A: |Q: ),但我们有结局\.

\.匹配文字句点。

对于 for 循环:

questions_and_answers = []
for line in string.splitlines():
    if line.startswith(("Q: ", "A: ")):
        questions_and_answers.append(line)
    else:
        questions_and_answers[-1] += line

# ['Q: This is a question. ', 'Q: This is a 2nd question on two lines. ', 'A: This is an answer. ', 'A: This is a 2nd answer on two lines.', "Q: Here's another question. ", 'A: And another answer.']```

推荐阅读