繁体   English   中英

正则表达式模式以在两个问题之间获得答案

[英]Regex pattern to get answers between two questions

如何在问题结尾(从 ? 之后开始)和下一个以“问题”开头的问题之前的文本之间获取文本?

他们的答案由新行分隔

import re
text = "Which feature is not part of the linux system?
pipe
2) dirx
ls
ps

Question 2 ("

output= re.findall(r'\?\s*(.*?)\s*Question\)', splitext).split('\n')
print(output)

您可以使用此正则表达式来匹配? Question

(?s)(?<=\?).+?(?=\nQuestion )

正则表达式演示

解释:

  • (?s) :启用 DOTALL 模式以确保. 匹配的换行符也
  • (?<=\\?) :回顾断言我们有? 就在当前位置之前
  • .+? : 匹配 1+ 个任何字符,包括换行符
  • (?=\\nQuestion ) : Lookahead 断言我们在当前位置之前有一个换行符,然后是Question

您可以使用捕获组,匹配之间不以问号结尾且不以Question开头的行

^.*\?((?:\n(?!.*\?$|Question\b).*)+)
  • ^字符串开始
  • .*\\? 匹配以?结尾的行
  • (捕获组 1 (将由 re.findall 返回)
    • (?:非捕获组作为一个整体重复
      • \\n(?!.*\\?$|Question\\b)匹配一个换行符,并断言该行不以? 或以问题开头
      • .*如果断言为真,则匹配整行
    • )*关闭非捕获组并可选择重复
  • )关闭第 1 组

正则表达式演示

例如

import re

text = ("Which feature is not part of the linux system?\n"
        "pipe\n"
        "2) dirx\n"
        "ls\n"
        "ps\n\n"
        "Question 2 (")

output = re.findall(r'^.*\?((?:\n(?!.*\?$|Question\b).*)*)', text)
print(output)

输出

['\npipe\n2) dirx\nls\nps\n']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM