拆分字符串的最佳方法是什么?
text = "hello there how are you"用Python?
所以我最终会得到这样的数组:
['hello there', 'there how', 'how are', 'are you']我试过这样做:
liste = re.findall('((\S+\W*){'+str(2)+'})', text)
for a in liste:
print(a[0])但我得到了:
hello there
how are
you如何使findall函数在搜索时只移动一个令牌?
发布于 2019-07-11 22:57:22
下面是使用re.findall的解决方案
>>> import re
>>> text = "hello there how are you"
>>> re.findall(r"(?=(?:(?:^|\W)(\S+\W\S+)(?:$|\W)))", text)
['hello there', 'there how', 'how are', 'are you']查看re:https://docs.python.org/3/library/re.html的Python
(?=...)前瞻性断言(?:...)非捕获规则括号https://stackoverflow.com/questions/56998097
复制相似问题