首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在python中使用regex拆分字符串

在python中使用regex拆分字符串
EN

Stack Overflow用户
提问于 2019-07-11 22:33:01
回答 6查看 502关注 0票数 2

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

代码语言:javascript
运行
复制
text = "hello there how are you"

用Python?

所以我最终会得到这样的数组:

代码语言:javascript
运行
复制
['hello there', 'there how', 'how are', 'are you']

我试过这样做:

代码语言:javascript
运行
复制
liste = re.findall('((\S+\W*){'+str(2)+'})', text)
for a in liste:
    print(a[0])

但我得到了:

代码语言:javascript
运行
复制
hello there 
how are 
you

如何使findall函数在搜索时只移动一个令牌?

EN

Stack Overflow用户

回答已采纳

发布于 2019-07-11 22:57:22

下面是使用re.findall的解决方案

代码语言:javascript
运行
复制
>>> 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']

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

  • (?=...)前瞻性断言
  • (?:...)非捕获规则括号
票数 3
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56998097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档