使用正则表达式拆分逗号、空格或分号分隔的字符串

4

我使用正则表达式 [,;\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']。对于正则表达式有什么建议吗?
3个回答

9

尝试:

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

8

以下是一些非常低技术的方法,仍然应该有效:

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

PS: 尽管正则表达式很有用,但我强烈建议您再三考虑它是否是此处的正确工具。尽管我不确定编译后的正则表达式的确切运行时间(我认为最多为O(n^2)),但它绝对不比string.replace的运行时间更快,而string.replace的运行时间为O(n)。因此,除非您需要使用正则表达式的其他原因,否则这个解决方案应该就能够满足您的需求。


感谢inspectorG4dget提供的PS。 - ghostcoder

4
好的,技术上说,拆分功能是有效的。在字符串 a,,b,c 中,它根据 ,,, 进行拆分,最终得到了 "a"、"b" 和 "c" 三个子串;而在字符串 a,,b,c, 中,它同样会根据 ,,, 和最后一个 , 进行拆分(因为它们都符合正则表达式!),最终得到的子串为 "a"、"b"、"c" 和 ""(即最后一个逗号和字符串结尾之间的内容)。
你可以采用几种方式来规避这个问题。
  • The empty string will only occur if there's a delimiter at the start or end of the string, so trim off any of these [,;\s] prior to splitting using str.strip:

    p.split(mystring.strip(',; \t\r\n'))
    
  • Remove the empty string after the splitting, using any method you please

    res = p.split(mystring)
    [r for r in res if r != '']
    # another option
    filter(None,res)
    
  • Even better, since you know you'll only get the empty string as either the first or last part of the split string (e.g. ,a,b,c or a,b,c,), don't iterate through the entire split:

    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]==''))]
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接