简体   繁体   中英

Using re.sub() in python how to replace certain phrase but only if there is more than one letter ahead of it

for example the text looks something like

sentence = "blah blah blah jnfskjndflah"

and i only want to replace "lah" with nothing only if there is more than one letter ahead of it with re.sub() on python

so just replace it in "jnfskjndflah" but not "blah" if that makes sense and the sentence will look like "blah blah blah jnfskjndf".

i had it as s = re.sub("[*az]lah", "", sentence) but the outcome was "blah blah blah jnfskjnd" (missing the f)

any help is appreciated!

You can you a positive lookbehing asserting 2 chars az for example

(?<=[a-z]{2})lah

Regex demo | Python demo

import re

sentence = "blah blah blah jnfskjndflah"
s = re.sub("(?<=[a-z]{2})lah", "", sentence)
print(s)

Output

blah blah blah jnfskjndf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM