python - Python 3 中的简单正则表达式替换“|”之间的文本 和“/”符号
问题描述
我想替换 '|' 之间的文本 和字符串(“|伊士曼柯达公司/”)中的 '/' 和 '!!!'。
s = '柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|伊士曼柯达公司/'
print(s)
s = re.sub(r'\|.*?\/.', '/!!!', s)
print('\t', s)
我首先在https://regex101.com/上测试了代码,它运行良好。
我不太明白为什么它没有在 python 中进行替换。
我尝试过的转义变体还包括:
s = re.sub(r'|.*?\/.', '!!!', s)
s = re.sub(r'|.*?/.', '!!!', s)
s = re.sub(r'\|.*?/.', '!!!', s)
每次字符串出来时都不变。
解决方案
您可以将您的正则表达式更改为这个,它使用环视来确保您要替换的内容之前|
和之后/
(?<=\|).*?(?=/)
检查这个 Python 代码,
import re
s = '柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|伊士曼柯达公司/'
print(s)
s = re.sub(r'(?<=\|).*?(?=/)', '!!!', s)
print(s)
打印如您所愿,
柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|伊士曼柯达公司/
柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|!!!/
推荐阅读
- angularjs - 如何在angularjs中使用alasql包装文本内容
- doxygen - 将 Doyxgen xml 输出转换为 DITA
- jquery - jQuery UI 调整大小,同时保持相同的整体宽度
- regex - 使用 RegEx 将大写转换为 title()
- actions-on-google - 我可以阻止参数被截断吗?
- javascript - 使用 Angularjs 在动态列表项中添加事件 stopPropagation
- android - 在 Realm 中实现回调并将其设置在 Presenter MVP 中以进行异步工作
- jquery - jQuery 序列化添加名为 '_' 的附加字段(下划线)
- php - 如何在 laravel 5.6 中使用 ajax 将数据从控制器传递到视图
- google-cloud-platform - 来自`datastore.NewQuery("").Ancestor(myKey)`的`datastore:invalid entity type`错误