首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >regex:使用Python中的组名进行条件替换

regex:使用Python中的组名进行条件替换
EN

Stack Overflow用户
提问于 2016-12-15 11:29:33
回答 1查看 82关注 0票数 0

string1:"4-5%“和string2:"5%”

预期输出:“%4到% 5",”% 5“。

我的正则表达式:

代码语言:javascript
复制
percent = 
    {
        "pattern": "(?P<range>(?P<from>[\d.]+)(%)?[?\-~ ~〜~—])?(?P<to>[\d.]+)%",
        "repl": r"(?(range)percent \g<from>to )percent\g<to>)",
        "string": thestring
    }

print re.sub(**percent)

对于第一个(percent["string"]="4-5%"),我得到的是(?(range)percent 5 to)percent 7),而对于第二个(当string=为“5%”),它就不起作用了。

我知道repl的值不能包含条件,但是(如何)我可以实现我想要的东西?在这个上下文中,我只能使用两个正则表达式吗?

EN

回答 1

Stack Overflow用户

发布于 2016-12-15 12:53:06

像这样的东西?

代码语言:javascript
复制
import re

a="""
4-5%
hello world 4-5% hello world
5%
"""
print re.sub(r'(\d)%', r'\1', re.sub(r'-',r' to ',re.sub(r'(\d(?=(-\d)?%))',r'percent \1',a)))

输出:

代码语言:javascript
复制
percent 4 to percent 5
hello world percent 4 to percent 5 hello world
percent 5
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41155966

复制
相关文章

相似问题

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