[英]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.