2014-02-21 26 views
1

我有一個這樣的字符串:蟒蛇上下文敏感的正則表達式解析hierchical文本結構

Group 1: 
Line A 
Line B 
Line C 
Group 2: 
Line A 
Line B 

我想知道是否有可能與結果是像一個正則表達式解析此:

Group: 1, Line: A 
Group: 1, Line: B 
Group: 1, Line: C 
Group: 2, Line: A 
Group: 2, Line: B 

這是我到目前爲止有:

regex = r'''(?x) 
(?<=Group\s(\d):\n) 
(?:Line\s\w+\n)* 
Line\s(\w+) 
''' 
match_iter = re.finditer(regex,test,re.M|re.S|re.I) 
for m in match_iter: 
    print m.groups() 

但是,這是錯誤的,因爲我只得到:

('1', 'C') 
('2', 'B') 

而我卡在這裏......任何想法我怎麼能做到這一點? (或者如果它甚至有可能與重新做)

編輯: 我要尋找一個正則表達式唯一的解決辦法,因爲我試圖堵塞這個到光框架,只需要一個正則表達式,而不是任意代碼。我不能使用任何狀態等。這意味着在上面的代碼片段中,我只能改變'正則表達式'的值。

回答

0
import re 

regex = re.compile("(Group) (\d+)|(Line) (\w+)") 

INPUT = """ 
Group 1: 
Line A 
Line B 
Line C 
Group 2: 
Line A 
Line B""" 

def main(): 
    group, line = None, None 
    for match in regex.finditer(INPUT): 
     if match.group(1): 
      # found a Group 
      group = match.group(2) 
     else: 
      # found a Line 
      line = match.group(4) 
      print("Group: {group}, Line: {line}".format(group=group, line=line)) 

if __name__=="__main__": 
    main() 

回報

Group: 1, Line: A 
Group: 1, Line: B 
Group: 1, Line: C 
Group: 2, Line: A 
Group: 2, Line: B 
+0

任何沒有狀態的方法?它只需要是一個正則表達式,因爲我試圖將它插入一個只需要正則表達式而不是任意代碼的簡單框架。 – jeff

+0

@jeff:我不相信用單個正則表達式是可能的;你使用什麼框架?也許我們可以提出另一種方法? –

+0

我們有我們自己的框架,我們用它來修改某些命令的輸出。例如,在上面的字符串中,我可以輸入類似(1,B)的內容作爲關鍵字,然後將該行的值或行中的某些項目更改爲任意值。 – jeff

0

這爲我提供了不少娛樂今晚。只改變你的正則表達式的約束是非常有趣的。最接近我可以給你想要的是兩種選擇。

txt = 'Group 1:\nLine A\nLine B\nLine C\nGroup 2:\nLine A\nLine B' 

re.findall(r'''(?:Group)(\d).*?(?:\nLine)?([A-Z]+)(?:\nLine)?([A-Z]+)(?:\nLine)?([A-Z]+)?''', txt, re.S) 

regex = r'''(?:Group)(\d) 
      .*? 
      (?:\nLine)?([A-Z]+) # Must Match 
      (?:\nLine)?([A-Z]+) # Must Match 
      (?:\nLine)?([A-Z]+)? # The matching group made optional by the ? 
     ''' 
re.findall(regex, txt, re.S|re.X) 

返回:

[('1', 'A', 'B', 'C'), 
('2', 'A', 'B', '')] 

第二個選項是在休的建議的變化,但我使本集團,並與(?:...)線非捕獲:

re.findall(r'''(?:Group)(\d)+|(?:Line)([A-Z]+)''', txt, re.S) 

返回:

[('1', ''), 
('', 'A'), 
('', 'B'), 
('', 'C'), 
('2', ''), 
('', 'A'), 
('', 'B')] 

由於您似乎無法對數據做任何有趣的事情,因此我進一步操縱它幾乎沒有意義。我認爲我更喜歡後者的解決方案,因爲它更容易擴展到數據的變化,而前者不具有可擴展性。 (你有多少個可選的匹配組將被粘貼到你的正則表達式中?)