python Python正则表达式通过两个分隔符之一拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/618551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:29:05  来源:igfitidea点击:

Python regex split a string by one of two delimiters

pythonregex

提问by interstar

I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space.

我想分割一串电子邮件地址,这些地址可以用逗号和空格的任意组合分隔。

And I thought it would be pretty straight-forward :

我认为这会很简单:

sep = re.compile('(\s*,*)+')
print sep.split("""[email protected], [email protected]

   [email protected],,[email protected]""")

But it isn't. I can't find a regex that won't leave some empty slots like this :

但事实并非如此。我找不到一个不会像这样留下一些空槽的正则表达式:

['[email protected]', '', '[email protected]', '', '[email protected]', '', '[email protected]']

I've tried various combinations, but none seem to work. Is this, in fact, possible, with regex?

我尝试了各种组合,但似乎都不起作用。事实上,使用正则表达式可能吗?

回答by interstar

Doh!

呸!

It's just this.

就是这个。

sep = re.compile('[\s,]+')

回答by Mykola Golubyev

without re

无需重新

line = 'e@d , f@g, 7@g'

addresses = line.split(',')    
addresses = [ address.strip() for address in addresses ]

回答by S.Lott

I like the following...

我喜欢以下...

>>> sep= re.compile( r',*\s*' )
>>> sep.split("""[email protected], [email protected]

   [email protected],,[email protected]""")
['[email protected]', '[email protected]', '[email protected]', '[email protected]']

Which also seems to work on your test data.

这似乎也适用于您的测试数据。