2012-11-13 45 views
0

匹配,我有以下字符串數據:模式與多個非空格字符

data = "*****''[[dogs and cats]]''/n" 

我想用正則表達式在Python中提取字符串。所有數據都封裝在雙引號「」中。什麼是我用,所以我可以得到下面的通配符:

print data.groups(1) 
print data.groups(2) 
print data.groups(3) 

'dogs' 
'and' 
'cats' 

編輯:到目前爲止,我有一些很長的這個

test = re.search("\\S*****''[[(.+) (.+) (.+)\\S]]''", "*****''[[dogs and cats]]''\n") 
    print test.group(1) 
+3

你有什麼企圖這種自行解決? –

+0

你說你想要的數據是雙引號,但是在文本中唯一的雙引號醃肉nd python字符串。你的意思是兩個單引號''''(而不是雙引號''')嗎?非字母字符是否應該被忽略(例如方括號)? – Blckknght

+0

另外,您可能想要接受以前的問題的答案,鼓勵人們更多地幫助你! – Blckknght

回答

1

有些人在遇到問題時想:「我知道,我會用正則表達式。」現在他們有兩個問題。「傑米Zawinski撰寫

data = "*****''[[dogs and cats]]''/n" 
start = data.find('[')+2 
end = data.find(']') 
answer = data[start:end].split() 

print answer[0] 
print answer[1] 
print answer[2] 
+0

感謝您的洞察和引用!謝謝@Moshe – hylaeus

1

線很難知道你到底是什麼尋找,但我會假設你正在尋找一個正則表達式來分析一個或多個由非字母數字字符包圍的空格分隔的單詞。

data = "*****''[[dogs and cats]]''/n" 

# this pulls out the 'dogs and cats' substring 
interior = re.match(r'\W*([\w ]*)\W*', data).group(1) 

words = interior.split() 

print words 
# => ['dogs', 'and', 'cats'] 

雖然這會對您的需求做出很多假設。取決於你想要的東西,正則表達式可能不是最好的工具。

+0

是的,這對我來說是一件非常棒的事情,謝謝@Aniket – hylaeus

1

正如有人說,這是使用相當簡單的一個額外split步:

data = "***rubbish**''[[dogs and cats]]''**more rubbish***" 
words = re.findall('\[\[(.+?)\]\]', data)[0].split() # 'dogs', 'and', 'cats' 

一個單一的表達也是可能的,但它看起來相當混亂:

rr = r''' 
    (?x) 
    (\w+) 
    (?= 
     (?: 
      (?!\[\[) 
      . 
     )*? 
     \]\] 
    ) 
''' 
words = re.findall(rr, data) # 'dogs', 'and', 'cats' 
+0

拆分是一個很好的解決方法,雖然有點令人困惑。謝謝@ thg435。 – hylaeus

相關問題