繁体   English   中英

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

[英]split a comma, space, or semicolon separated string using regex

我使用正则表达式[,; \\ 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']。

关于正则表达式的任何建议?

这是一个非常低技术的东西应该仍然有效:

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

PS :虽然正则表达式非常有用,但我强烈建议再考虑一下它是否适合这里的工作。 虽然我不确定编译正则表达式的确切运行时是什么(我最多想的是O(n ^ 2)),但它绝对不比O(n)快,后者是string.replace的运行时。 因此,除非您需要使用正则表达式的原因不同,否则应使用此解决方案进行设置

尝试:

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

嗯,分裂在技术上确实有效。 a,,b,c ,它分裂的,,,留下“A”, “B”和“C”。 a,,b,c, ,它分裂的,,,最后, (因为他们都匹配正则表达式!)。 这些delmiters周围的字符串是“a”,“b”,“c”和“”(在最后一个逗号和字符串结尾之间)。

你可以通过几种方法来规避这个问题。

  • 只有在字符串的开头或结尾有分隔符时才会出现空字符串,因此在使用str.strip拆分之前修剪掉这些[,;\\s]任何str.strip

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM