python - 在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
函数在搜索时只移动一个标记?
解决方案
这是一个解决方案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 文档re
:https ://docs.python.org/3/library/re.html
(?=...)
前瞻断言(?:...)
非捕获正则括号
推荐阅读
- powershell - PowerShell:如何定义具有固定参数的别名,并且可以使用附加参数进行扩展?
- javascript - 在反应钩子,函数语句或常量中定义函数?
- javascript - 如何使用 Css 按钮显示和隐藏视频播放器?
- c# - 如何从解决方案中的现有项目中解决 c# CS0006 错误
- php - 在带有输出格式的 txt 文件 Linux 命令行上显示 php 输出
- python - PySide2 - 调用 QFileSystemModel.index() 时程序崩溃
- powershell - Powershell剪贴板问题
- c# - 使用 asp.net web api 读取 cookie
- ios - 无法在 Xcode 中归档应用以供提交
- seo - 仅允许 Googlebot 将所有内容编入索引