python 由于转义序列,正则表达式子不工作
python regex sub not working due to escape sequence
我有这样的文字。 -> Roberto 是一名保险代理人,销售两种保单:$$\$$50,000$$ 保单和 $$\$$100,000$$ 保单。上个月,他的目标是至少卖出 57 份保单。虽然他没有达到他的目标,但他出售的保单总价值超过 $$\$$3,000,000$$。以下哪个不等式系统描述了 Roberto 出售的 $$x$$($$\$$50,000$$ 保单的可能数量)和 $$y$$($$\$$100,000$$ 保单的可能数量)上个月?
我想替换包含美元符号的表达式,例如 $$\$$50,000$$。删除 $$y$$ 之类的东西效果很好,但包含转义序列的表达式效果不佳。
这是我使用的代码。
re.sub("$$$$.*?$$", "", text)
这行不通,我发现\是一个escape str,所以应该写成\。所以我替换了下面的表达式。
re.sub("$$\$$.*?$$", "", text)
然而,这又没有奏效。我究竟做错了什么 ?非常感谢...
字符 $
是正则表达式元字符,因此如果要引用文字 $
:
则需要转义
text = """Roberto is an insurance agent who sells two types of policies: a $$$,000$$ policy and a $$$0,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 $$$,000,000$$. Which of the following systems of inequalities describes $$x$$, the possible number of $$$,000$$ policies, and $$y$$, the possible number of $$$0,000$$ policies, that Roberto sold last month?"""
output = re.sub(r'$$(?:\$$)?.*?$$', '', text)
print(output)
以上模式使 $$
可选,以涵盖所有情况。
我有这样的文字。 -> Roberto 是一名保险代理人,销售两种保单:$$\$$50,000$$ 保单和 $$\$$100,000$$ 保单。上个月,他的目标是至少卖出 57 份保单。虽然他没有达到他的目标,但他出售的保单总价值超过 $$\$$3,000,000$$。以下哪个不等式系统描述了 Roberto 出售的 $$x$$($$\$$50,000$$ 保单的可能数量)和 $$y$$($$\$$100,000$$ 保单的可能数量)上个月?
我想替换包含美元符号的表达式,例如 $$\$$50,000$$。删除 $$y$$ 之类的东西效果很好,但包含转义序列的表达式效果不佳。
这是我使用的代码。
re.sub("$$$$.*?$$", "", text)
这行不通,我发现\是一个escape str,所以应该写成\。所以我替换了下面的表达式。
re.sub("$$\$$.*?$$", "", text)
然而,这又没有奏效。我究竟做错了什么 ?非常感谢...
字符 $
是正则表达式元字符,因此如果要引用文字 $
:
text = """Roberto is an insurance agent who sells two types of policies: a $$$,000$$ policy and a $$$0,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 $$$,000,000$$. Which of the following systems of inequalities describes $$x$$, the possible number of $$$,000$$ policies, and $$y$$, the possible number of $$$0,000$$ policies, that Roberto sold last month?"""
output = re.sub(r'$$(?:\$$)?.*?$$', '', text)
print(output)
以上模式使 $$
可选,以涵盖所有情况。