2011-03-31 43 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

相关问题