首页 > 解决方案 > 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)

每次字符串出来时都不变。

标签: pythonregex

解决方案


您可以将您的正则表达式更改为这个,它使用环视来确保您要替换的内容之前|和之后/

(?<=\|).*?(?=/)

检查这个 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 伊士曼柯達公司|!!!/

在线 Python 演示


推荐阅读