python - 使用 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:”。
解决方案
我建议为此使用 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.']```
推荐阅读
- reactjs - showNotification api 不适用于 create-react-app
- postgresql - Postgres 的 NiFi 数据库连接
- c# - 如何使用c#将文本文件的一行读入数组,然后按索引获取元素
- python - 如何根据熊猫中的两列条件提取数据
- cookies - 在开玩笑测试时从 Cookies (js-cookie) 中检索数据
- python - altair 无法创建选择组合
- java - corda 实现通用保险库查询
- postgresql - 解释一个有限制和顺序的执行计划
- omnet++ - 对 SUMO、VEINS 和 OMNET++ 的怀疑
- vba - 如何创建循环以打开特定文件并保存到每个循环的特定选项卡