【发布时间】:2017-02-23 15:59:55
【问题描述】:
我想做这样的事情:
import re
s = 'This is a test'
re.split('(?<= )', s)
添加返回类似这样的内容:
['This ', 'is ', 'a ', 'test']
但这不起作用。
谁能建议一种简单的方法来根据正则表达式拆分字符串(我的实际代码更复杂,并且确实需要正则表达式)而不丢弃任何内容?
【问题讨论】:
-
类似
[i for i in re.split('([^ ]+ ?)',s) if i]? -
@fredtantini 您应该将其添加为答案
-
@fredtantini 太棒了!我曾经说过 Perl 是 21 世纪的 APL...
-
@fredtantini 将正则表达式放在括号中似乎会改变
re.split的行为。这在某处有记录吗? -
@BrentBaccala 引用 docs.python.org/2/library/re.html#re.split
If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list