通过使用
re.split()
函数:
>>> re.split(r'(this|into|ones)', "Let's split this string into many small ones")
["Let's split ", 'this', ' string ', 'into', ' many small ', 'ones', '']
通过将要分割的单词放入捕获组中,输出将包含我们要分割的单词。
如果您需要去掉空格,请在re.split()
输出上使用map(str.strip, result)
:
>>> map(str.strip, re.split(r'(this|into|ones)', "Let's split this string into many small ones"))
["Let's split", 'this', 'string', 'into', 'many small', 'ones', '']
如果需要,您可以使用filter(None, result)
来删除任何空字符串:
>>> filter(None, map(str.strip, re.split(r'(this|into|ones)', "Let's split this string into many small ones")))
["Let's split", 'this', 'string', 'into', 'many small', 'ones']
为了按单词分割但保持它们连接到后面的组,您需要使用先行断言:
>>> re.split(r'\s(?=(?:this|into|ones)\b)', "Let's split this string into many small ones")
["Let's split", 'this string', 'into many small', 'ones']
现在我们正在根据空格进行分割,但仅限于紧跟着一组单词中的一个(
this
、
into
和
ones
)的空格。