2012-02-25 12 views
3

我第一次來這裏,標題是不好的,我知道:)多個同名組的定義,或者如果系統

好了,這就是我想要做

輸入可能性1:SOMETHING BLAH always same words here (here comes date/time text, called group 1) [group 2 text]: (group 3 text) END

輸入2:SOMETHING BLAH [group 2 text] always same words here (here comes date/time text, called group 1): (group 3 text) END

組2可出現

之前或之後現在,使用Python和模塊重新,是有可能匹配eithe這些輸入只使用1個正則表達式?

例(很顯然,這樣的事情是不可能的,因爲它包含同名組):

"SOMETHING BLAH (always same words here \((?P<group1>.{1,40})\) \[(?P<group2>.*?)\]: \((?P<group3>.*?)\)|\[(?P<group2>.*?)\] always same words here \((?P<group1>.{1,40})\): (group 3 text)) END", re.DOTALL 

這只是什麼我嘗試做

+0

如果標題是壞的,可以考慮將其固定。這只是關於正則表達式組的名稱。考慮改變標題以反映實際問題中的實際情況。 – 2012-02-26 01:01:31

+0

爲什麼'顯然不可能'?如果這是真的,那將是一個非常愚蠢的限制。你一直在用Perl做這樣的事情;實際上,您的模式在Perl中使用精確的語法編譯得很好。你看過Matthew Barnett的Python的regex模塊嗎?我相信它有一個分支重置操作,可以幫助你。 – tchrist 2012-02-26 01:55:02

+0

不可能在python中,其他一些langs是的,就像我聽說的.NET一樣,Perl就像你說的那樣。目前很糟糕的事情,不知道在Python 3.0 – Intelligence404 2012-03-05 13:27:53

回答

0

當然,你可以使用可選組的exmp:

>>> patt = re.compile("foo (?P<name>[0-9]+)?") 
>>> patt.search("blah foo 999 bar").groupdict() 
{'name': '999'} 
>>> patt.search("blah foo bar").groupdict() 
{'name': None} 

你例如,稍微簡化爲長度:

prefix (?P<optional1>\[.*?\])? same-words \((?P<date>.*?)\)(?P<optional2> \[.*?\])?: \((?P<g3>.*?)\) END 

然後,一旦你有一個比賽,你可以這樣做:

d = patt.search(str).groupdict() 
g2 = d["optional1"] if d["optional1"] is not None else d["optional2"] 
+0

中是否有可能出現這種情況,感謝這個解決方案,我不喜歡再使用一個測試,但似乎現在沒有別的辦法了。我正在用這個。謝謝 – Intelligence404 2012-03-05 13:26:45

相關問題