python - 由于转义序列,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)
然而,这又没有奏效。我究竟做错了什么 ?非常感谢提前...
解决方案
该字符$
是一个正则表达式元字符,因此如果打算引用文字,则需要对其进行转义$
:
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)
上面的模式是\$$
可选的,涵盖所有情况。
推荐阅读
- node.js - 在 iframe 中加载时被 iOS Safari 阻止的身份验证 cookie
- sql - 基于另一个参数的条件 where 子句
- angular - 在移动角度7上滚动时防止关闭工具提示
- python - dill.dump_session 不能与 getpass 一起使用
- html - 如何使用 Jekyll 显示单个帖子的摘录
- python - 如何在 pycryptodome 中为 chacha20-poly1305 设置块计数器
- php - 在 php artisan tinker 中保存更改
- magento - Magento 1.9 - 如何根据客户群更新产品价格
- html - 如何防止附加在html表单文本区域中的回车符?
- c# - ASP.NET Core 2.2 实体继承和数据库引用