2012-03-16 69 views
0

首先代碼:Python的正則表達式失敗

str = "(suf) some text here (stuff here)" 
r = re.split(r"(?<=[\)]) (?=[\w\(])", str) 

這是我用來解析格式文件的一些代碼示例。作爲結果,我基本上試圖獲得('suf','some text here (stuff here)')。我嘗試了各種排列,但它一直給我的是整個字符串。

+4

當我運行它,我得到['(suf)','一些文本(這裏的東西)'],是不是你想要的? – xitrium 2012-03-16 17:27:21

+0

也適用於我。你確定這就是你失敗時使用的(真實)字符串嗎?嘗試提供它的'repr()'值。 – 2012-03-16 17:31:51

+0

我無法重現您的問題 – Atif 2012-03-16 17:31:58

回答

1

你在分割字符串,而不是捕獲內部匹配。 如果你想捕捉的第一架字符串裏面和一切爲兩個對象,這一點也適用match(可能與分工作了,這僅僅是我會怎麼做):

str = "(suf) some text here (stuff here)" 
# capture anything inside first set of brackets 
# then capture everything else, dropping any spaces between them 
r = re.match(r"^\((.*?)\)\s*(.*)", str) 
r.groups() 
r.group(1) # group(0) is the full original string 
r.group(2)