首页 > 解决方案 > 在python中使用正则表达式拆分字符串

问题描述

拆分字符串的最佳方法是什么

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函数在搜索时只移动一个标记?

标签: pythonregexsplit

解决方案


这是一个解决方案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']

查看 Python 文档rehttps ://docs.python.org/3/library/re.html

  • (?=...)前瞻断言
  • (?:...)非捕获正则括号

推荐阅读