如何在問題結尾(從 ? 之后開始)和下一個以“問題”開頭的問題之前的文本之間獲取文本?
他們的答案由新行分隔
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)
uj5u.com熱心網友回復:
您可以使用此正則運算式來匹配?和之間的所需文本Question:
(?s)(?<=\?). ?(?=\nQuestion )
正則運算式演示
解釋:
(?s): 啟用 DOTALL 模式以確保.匹配的換行符也(?<=\?): Lookbehind 斷言我們?在當前位置之前. ?: 匹配 1 個任何字符,包括換行符(?=\nQuestion ): Lookahead 斷言我們Question在當前位置之前有一個換行符
uj5u.com熱心網友回復:
您可以使用捕獲組,匹配之間的行不以問號結尾,也不以 Question
^.*\?((?:\n(?!.*\?$|Question\b).*) )
^字串的開始.*\?匹配結束于的行?(捕獲組 1 (將由 re.findall 回傳)(?:非捕獲組作為一個整體重復\n(?!.*\?$|Question\b)匹配換行符,并斷言該行不?以 Question結尾或開頭.*如果斷言為真,則匹配整行
)*關閉非捕獲組并可選擇重復
)關閉第 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']
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/337893.html
上一篇:Python正則運算式正向后視
