2011-03-31 85 views
0

python的新手和我無法獲得我想要的正則表達式的函數。基本上我有一個字符串,看起來像"Hello, World, Nice",我需要將它轉換成分隔符爲,的列表。最終的結果應該像['Hello', 'World', 'Nice']通過正則表達式分割字符串

re.split(',', string)

基本上,結果我得到的是 ['Hello', ' World', ' Nice']。 我知道一個解決方案通過不同的方法,但我想使用正則表達式。

非常感謝。

回答

3

假設,即空白可以是任意的,有兩種解決方案,浮現在腦海中:

re.split(r'\s*,\s*', string) 
#   ^- zero or more whitespace incl. tabs and newlines 
# the r'' syntax preserves the backslash from being interpreted 
# as escape sequence 

map(str.strip, string.split(',')) 
# ^- apply the 'strip' function (~ 'trim' in other languages) to all matches 

我會去與後來的。如果你經常在你的代碼中進行分割,優點是跳過正則表達式(儘管它不會總結,直到你經常將分割爲)。

+0

真棒,像一個對待感謝工作! – Benji 2011-03-31 07:49:22

+0

不客氣。 – Boldewyn 2011-03-31 09:02:15

+0

'r'原始字符串保護可以被刪除,因爲'\ s'不被Python解釋。 – EOL 2011-03-31 09:09:39

0

', '分割,重新使用空間

re.split(', ', string) 
0
>>> a = "Hello, World, Nice" 
>>> a.split(", ") 
['Hello', 'World', 'Nice'] 
>>> 

>>> import re 
>>> re.split(', ',a) 
['Hello', 'World', 'Nice'] 
>>> 
0
re.split(', ', string) 

你想要做什麼。

0

如果您沒有特定的高級要求,則確實不需要重新組裝模塊。

>>> "Hello, World, Nice".split(",") 
['Hello', ' World', ' Nice'] 
>>> map(str.strip, "Hello, World, Nice".split(",")) 
['Hello', 'World', 'Nice'] 

如果你真的堅持要。

>>> re.split('\s*,\s*', "Hello, World, Nice") 
['Hello', 'World', 'Nice'] 
-1

嘗試此正則表達式分裂

>>> a = "Hello, World, Nice" 
>>> a.split("[ ,\\,]") 

在正則表達式第一是空間和第二是逗號

+0

這不是正則表達式分割。 'str.split()'不使用正則表達式。如果可以的話,它也會分裂一個「Hello World」。 – Boldewyn 2011-03-31 07:42:40

0

稍微更健壯的解決方案:

>>> import re 
>>> pattern = re.compile(' *, *') 
>>> l = "Hello, World , Nice" 
>>> pattern.split(l) 
['Hello', 'World', 'Nice'] 
>>> 
3

哈,另一種解決方案的w/o的正則表達式:

x="Hello, World, Nice" 
[y.strip() for y in x.split(",")] 
+0

+1爲列表理解。我喜歡那種語法。 – Boldewyn 2011-03-31 09:01:47