Zhiming010
Zhiming010

Reputation: 313

Simple Regex in Python Three to replace text between '|' and '/' symbols

I want to replace the text between the '|' and '/' in the string ("|伊士曼柯达公司/") with '!!!'.

s = '柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|伊士曼柯达公司/'
print(s)
s = re.sub(r'\|.*?\/.', '/!!!', s)
print('\t', s)

I tested the code first on https://regex101.com/, and it worked perfectly.

I can't quite figure out why it's not doing the replacement in python.

Variant's of escaping I've tried also include:

s = re.sub(r'|.*?\/.', '!!!', s)
s = re.sub(r'|.*?/.', '!!!', s)
s = re.sub(r'\|.*?/.', '!!!', s)

Each time the string comes out unchanged.

Upvotes: 0

Views: 48

Answers (1)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can change your regex to this one, which uses lookarounds to ensure what you want to replace is preceded by | and followed by /

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

Check this Python code,

import re

s = '柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|伊士曼柯达公司/'
print(s)
s = re.sub(r'(?<=\|).*?(?=/)', '!!!', s)
print(s)

Prints like you expect,

柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|伊士曼柯达公司/
柯達⑀柯达⑀ /Kodak (brand, US film company)/full name Eastman Kodak Company 伊士曼柯達公司|!!!/

Online Python Demo

Upvotes: 1

Related Questions