python:用逗号和点后分割字符串

时间:2014-01-02 23:25:35

标签: python regex

我有一段代码用逗号和点分隔字符串(但不是当数字在逗号或点之前或之后)时:

text = "This is, a sample text. Some more text. $1,200 test."
print re.split('(?<!\d)[,.]|[,.](?!\d)', text)

结果是:

['This is', ' a sample text', ' Some more text', ' $1,200 test', '']

我不想丢失逗号和圆点。所以我要找的是:

['This is,', 'a sample text.', 'Some more text.', '$1,200 test.']

此外,如果text末尾有一个点,它会在列表末尾产生一个空字符串。此外,在分割弦的开头有白色空格。没有使用re是否有更好的方法?你会怎么做?

1 个答案:

答案 0 :(得分:7)

不幸的是,你不能在零长度匹配上使用re.split(),所以除非你能保证在逗号或点之后会有空格,否则你需要使用不同的方法。

以下是使用re.findall()的一个选项:

>>> text = "This is, a sample text. Some more text. $1,200 test."
>>> print re.findall(r'(?:\d[,.]|[^,.])*(?:[,.]|$)', text)
['This is,', ' a sample text.', ' Some more text.', ' $1,200 test.', '']

这不会删除空格,如果字符串以逗号或点结尾,您将在结尾处得到一个空匹配,但这些很容易修复。

如果可以安全地假设在每个逗号和点后面都会有空格,那么我们就可以在该空格上拆分字符串,这样可以使它更简单:

>>> print re.split(r'(?<=[,.])(?<!\d.)\s', text)
['This is,', 'a sample text.', 'Some more text.', '$1,200 test.']