string1:"4-5%“和string2:"5%”
预期输出:“%4到% 5",”% 5“。
我的正则表达式:
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的值不能包含条件,但是(如何)我可以实现我想要的东西?在这个上下文中,我只能使用两个正则表达式吗?
发布于 2016-12-15 12:53:06
像这样的东西?
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)))输出:
percent 4 to percent 5
hello world percent 4 to percent 5 hello world
percent 5https://stackoverflow.com/questions/41155966
复制相似问题