替换子字符串,并进行额外处理

时间:2017-05-01 17:37:46

标签: python regex

我正在寻找一种pythonic方法来替换字符串中的子字符串,类似于re.sub,但需要对找到的文本进行额外处理。它可以通过纯正则表达式语法实现,但它很快变得不可读,这比简单更难 - 实际上很难扩展/调试。

这是我需要实现的目标:

输入字符串:text1 (2, 100) text2 (34,23) text3

输出:相同的字符串,但使用值12和14将(2, 100)包装到HTML代码中;同样适用于(34, 23)。类似的东西:

text1 <span data-coord='{"x": 0.02, "y": 1}'>(2, 100)</span>
text2 <span data-coord='{"x": 0.34, "y": 0.23}'>(34, 23)</span> 
text3

通过与re.finditer的匹配进行迭代似乎是一种合理的解决方案,但如何获取其余文本呢?

编辑:数字可能是一到三位数,介于0和100之间。

脚注:我真的更喜欢有一个解决方案,其中找到的x和y组是我自定义函数的输入,可以完全自由地使用找到的组。例如。做错误处理:如果数字超出0 ... 100的范围,我可能想用红色突出显示它。我确信我也可以用正则表达式来定义这种行为,但我发现它错了:正则表达式用于文本处理,而不是数字操作。它掩盖了代码的逻辑。

2 个答案:

答案 0 :(得分:3)

您可以使用

import re

rx = re.compile(r'\((?P<x>\d+),\s*(?P<y>\d+)\)')

# before
string = "text1 (12, 14) text2 (34,23) text3"

def convert(match):
    return '''<span data-coord='{{"x": 0.{}, "y": 0.{}"}}'>{}</span>'''.format(
            match.group('x'),
            match.group('y'),
            match.group(0)
    )

string = rx.sub(convert, string)

print(string)
# text1 <span data-coord='{"x": 0.12, "y": 0.14"}'>(12, 14)</span> 
# text2 <span data-coord='{"x": 0.34, "y": 0.23"}'>(34,23)</span>
# text3

有效地将convert功能与.format()

结合使用

答案 1 :(得分:1)

正则表达式非常简单:

>>> re.sub(r'\((\d+),\s*(\d+)\)', r'''<span data-coord='{"x": 0.\g<1>, "y": 0.\g<2>}'>(\g<1>, \g<2>)</span>''', text)
text1 <span data-coord='{"x": 0.12, "y": 0.14}'>(12, 14)</span> text2 <span data-coord='{"x": 0.34, "y": 0.23}'>(34, 23)</span> text3

然后您可以使用https://msdn.microsoft.com/en-us/library/ee706941(v=vs.110).aspx进行分组:

{{1}}