首页 > 解决方案 > 由于转义序列,python regex sub 无法正常工作

问题描述

我有这样的文字。-> Roberto 是一名保险代理人,他销售两种类型的保单:$$\$$$50,000$$ 保单和 $$\$$$100,000$$ 保单。上个月,他的目标是销售至少 57 份保单。虽然他没有达到目标,但他出售的保单总价值超过 $$\$$3,000,000$$。以下哪个不等式系统描述了 Roberto 出售的 $$x$$($$\$$$50,000$$ 保单的可能数量)和 $$y$$($$\$$100,000$$ 保单的可能数量)上个月?

我想替换包含美元符号的表达式,例如 $$\$$50,000$$。删除诸如 $$y$$ 之类的东西效果很好,但是包含转义序列的表达式效果不佳。

这是我使用的代码。

re.sub("$$\$$.*?$$", "", text)

这不起作用,我发现\是一个转义str,所以应该写成\。所以我替换了下面的表达式。

re.sub("$$\\$$.*?$$", "", text)

然而,这又没有奏效。我究竟做错了什么 ?非常感谢提前...

标签: pythonregexescapestring

解决方案


该字符$是一个正则表达式元字符,因此如果打算引用文字,则需要对其进行转义$

text = """Roberto is an insurance agent who sells two types of policies: a $$\$$50,000$$ policy and a $$\$$100,000$$ policy. Last month, his goal was to sell at least 57 insurance policies. While he did not meet his goal, the total value of the policies he sold was over $$\$$3,000,000$$. Which of the following systems of inequalities describes $$x$$, the possible number of $$\$$50,000$$ policies, and $$y$$, the possible number of $$\$$100,000$$ policies, that Roberto sold last month?"""
output = re.sub(r'\$\$(?:\\\$\$)?.*?\$\$', '', text)
print(output)

上面的模式是\$$可选的,涵盖所有情况。


推荐阅读