[英]Python and RegEx: Repeating Pattern Not Working
我有一個帶有專有編程語言的文本文件,我想提取有關各種函數調用的相關信息。
函數的結構是:
函數名(input1, input2) 返回(output1, output2) 函數體
我正在使用 Python 和 RegEx 來捕獲這些信息,但我遇到了障礙。 我可以捕獲名稱、輸入和輸出,但我無法獲取所有函數體。
我使用以下行來捕獲此信息:
re.findall("(function)(.*?)\((.*?)\) returns \((.*?)\)(.*)", file_contents)
然而,在單詞“function”的第一個實例之后,這失敗了。 由於函數體中的嵌套語句,我無法使用特定關鍵字(我嘗試了不同的方法,但無法完全抓取整個函數體)來抓取最后一組(這將是函數體)。
如何在特定點之后對所有內容進行分組,然后重復該模式?
我想要的是: 'function', 'name', 'input1, input2', 'output1, output2', 'function body' 無限重復。 我希望最后一組在輸出之后抓取所有內容,然后在下一次出現“函數”一詞時重新啟動模式。 我嘗試了 (. ?) 和 (. ) 量詞的不同變體,但我似乎無法理解。
我不是專業的程序員,所以我不太擅長使用 RegEx 或 Python。 我知道的足以做最基本的事情。
這將抓取函數直到下一個函數。
有5個捕獲組。
如果使用 findall,則后處理為一組 5 以獲得結果。
(?s)(\\bfunction\\b)(.*?)\\((.*?)\\)\\s+returns\\s+\\((.*?)\\)((?:(?!\\bfunction\\b).)*)
https://regex101.com/r/PkfofA/1
展開
(?s)
( \b function \b ) # (1)
( .*? ) # (2)
\(
( .*? ) # (3)
\) \s+ returns \s+ \(
( .*? ) # (4)
\)
( # (5 start)
(?:
(?! \b function \b )
.
)*
) # (5 end)
我想 finditer() 是一種更好地控制每組 5 個組的方法:
iter = re.finditer(r"(?s)(\bfunction\b)(.*?)\((.*?)\)\s+returns\s+\((.*?)\)((?:(?!\bfunction\b).)*)", target)
for result in iter:
g1 = result.group(1)
g2 = result.group(2)
g3 = result.group(3)
g4 = result.group(4)
g5 = result.group(5)
根據評論中的更多信息,我使用re.findall
中的re.findall
函數測試了以下正則表達式代碼,該函數適用於示例:
import re
file_contents = "function func1(in1 : bool; in2 : bool; in3 : bool) returns ( out : bool) var L1 : bool; L2 : bool; L5 : bool; L4 : bool; L3 : bool; begin L1 = L3 and L4; L2 = L1 or L5; out = L2; L5 = in3; L4 = in2; L3 = in1; end \n random code \nfunction func2(in1 : bool; in2 : bool; in3 : bool) returns ( out : bool) var L1 : bool; L2 : bool; L5 : bool; L4 : bool; L3 : bool; begin L1 = L3 and L4; L2 = L1 or L5; out = L2; L5 = in3; L4 = in2; L3 = in1;"
pattern = r"(function) (.*?)\((.*?)\) returns \((.*?)\) (.*)"
regex_results = re.findall( pattern, file_contents )
print( regex_results )
輸出:
[('function', 'func1', 'in1 : bool; in2 : bool; in3 : bool', 'out : bool', 'var L1: bool; L2 : bool; L5 : bool; L4 : bool; L3 : bool; begin L1 = L3 and L4; L2 = L1 or L5; out = L2; L5 = in3; L4 = in2; L3 = in1; end '), ('function', 'func2', 'in1 : bool; in2 : bool; in3 : bool', 'out : bool', 'var L1 : bool; L2 : bool; L5 : bool; L4 : bool; L3 : bool; begin L1 = L3和L4; L2 = L1或L5; out = L2; L5 = in3; L4 = in2; L3 = in1;')]
我想出了一種不同的方法來完成我想做的事情。
我使用了以下行:
re.split('(function )(.*?)\\((.*?)\\) returns \\((.*?)\\)', contents)
這將把我想要的東西分成一個列表。 然后我將列表分塊並將其分配給我擁有的變量。
感謝所有花時間回答的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.