2012-03-22 438 views
3

我使用正则表达式[,; \ s] +来分隔逗号,空格或分号分隔的字符串。使用正则表达式分割逗号,空格或分号分隔字符串

>>> p=re.compile('[,;\s]+') 
>>> mystring='a,,b,c' 
>>> p.split(mystring) 
['a', 'b', 'c'] 

当字符串有在最后一个逗号:如果字符串没有在最后一个逗号也能正常工作

>>> mystring='a,,b,c,' 
>>> p.split(mystring) 
['a', 'b', 'c', ''] 

我想在这种情况下,输出为[ 'a','b','c']。

对正则表达式的任何建议?

+2

是这对于一个csv – John 2012-03-22 01:07:54

+0

@johnthexiii都能跟得上 – ghostcoder 2012-03-22 01:09:12

回答

5

尝试:

str = 'a,,b,c,' 
re.findall(r'[^,;\s]+', str) 
+0

谢谢Qtax。这工作 – ghostcoder 2012-03-22 17:46:41

7

这里的东西非常的低技术应该仍然工作:

mystring='a,,b,c' 
for delim in ',;': 
    mystring = mystring.replace(delim, ' ') 
results = mystring.split() 

PS: 虽然正则表达式是非常有用的,我会强烈建议它是否是在这里工作的工具三思而后行。虽然我不确定编译正则表达式的确切运行时间是多少(我最多只想到O(n^2)),但它肯定不会比O(n)快,这是string.replace的运行时间。因此,除非有您需要使用正则表达式不同的原因,你应该用这种解决方案设置

+0

感谢inspectorG4dget为PS。 – ghostcoder 2012-03-22 17:47:31

3

那么,分裂技术上工作。在a,,b,c中,它在,,,上分开,留下“a”,“b”和“c”。在a,,b,c,,它分裂在,,,,和最后,(因为它们都匹配正则表达式!)。这些分隔符周围的字符串是“a”,“b”,“c”和“”(在最后一个逗号和字符串结尾之间)。

有几种方法可以规避这一点。如果有在开始或结束的字符串分隔符使用str.strip只会发生

  • 空字符串,所以剪掉这些[,;\s]到分割之前的:

    p.split(mystring.strip(',; \t\r\n')) 
    
  • 取出空拆分后的字符串,使用任何方法,你请

    res = p.split(mystring) 
    [r for r in res if r != ''] 
    # another option 
    filter(None,res) 
    
  • 更妙的是,因为你知道你只能得到电子作为拆分字符串的第一部分或最后一部分的空字符串(例如, ,a,b,ca,b,c,),不通过整个分裂迭代:

    res = p.slit(mystring) 
    # this one relies on coercing logical to numbers: 
    # if res[0] is '' it'll be 1:X, otherwise it'll be 0:X, 
    # where X is len(res) if res[-1] is not '', and len(res)-1 otherwise. 
    res[ res[0]=='':(len(res)-(res[-1]==''))] 
    
+0

感谢您的详细解释。 – ghostcoder 2012-03-22 17:46:26

相关问题