首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python regex循环每隔三项跳过一次

Python regex循环每隔三项跳过一次
EN

Stack Overflow用户
提问于 2019-07-22 15:43:35
回答 4查看 107关注 0票数 2

我正在做一个记号赋予器,我想把像"word- bound - with -hyphen“这样的字符串分成"word xxsep bound xxsep with xxsep hyphen”。

我试过这个:

代码语言:javascript
复制
import re

s = "words-bound-with-hyphen"
reg_m = re.compile("[\w\d]+-[\w\d]+")
reg = re.compile("([\w\d]+)-([\w\d]+)")
while(reg_m.match(s)):
    s = reg.sub(r"\1 xxsep \2", s)
print(s) #prints "words xxsep bound-with xxsep hyphen"

但这样就剩下每三个连字符的单词。

EN

回答 4

Stack Overflow用户

发布于 2019-07-22 16:00:02

您只需将连字符替换为正则表达式:

代码语言:javascript
复制
In [4]: re.sub("-", " xxsep ", "word-bound-with-hyphen")
Out[4]: 'word xxsep bound xxsep with xxsep hyphen'

或者使用字符串替换:

代码语言:javascript
复制
In [7]: "word-bound-with-hyphen".replace("-", " xxsep ")
Out[7]: 'word xxsep bound xxsep with xxsep hyphen'

您当前方法不起作用的原因是re.sub() returns groups,而word-boundbound-with重叠,与with-hyphen重叠。

票数 2
EN

Stack Overflow用户

发布于 2019-07-22 16:49:43

代码语言:javascript
复制
import re
s = "words-bound-with-hyphen"
re.sub('-',' xxsep ',s)

或不使用正则表达式

代码语言:javascript
复制
" xxsep ".join(x.split('-'))

在这里,列表将以-为分隔符进行分隔,然后使用"xxsep“连接

票数 2
EN

Stack Overflow用户

发布于 2019-07-22 16:07:10

如果您不想只替换所有连字符,而只替换前面和后面某些字符的连字符,那么使用regex lookback和lookahead。

代码语言:javascript
复制
import re
s = "words-bound-with-hyphen"
re.sub('(?<=[\w\d])-(?=[\w\d])',' xxsep ', s)
# result: 'words xxsep bound xxsep with xxsep hyphen'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57141244

复制
相关文章

相似问题

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