How to replace multiple occurrences of character when inside some other characters

Viewed 66

I have the following string:

someTxt="ABC -type X | aas < ISCO | ABB | TTI > kjhkjh"

I want to convert it into the following:

ABC -type X | aas &lt; ISCO \| ABB \| TTI &gt; kjhkjh

I am trying to do this in two steps (perhaps it can be better done in one!), as follows:

htmlTagTxt = re.sub(r'\<(.*)\>', r'&lt; \1 &gt;', someTxt)
print (htmlTagTxt)

This gives the following output:

ABC -type X | aas &lt;  ISCO | ABB | TTI  &gt; kjhkjh

Now I want to add the backslashes before the '|' characters.

cleanedHtmlTagTxt = re.sub(r'(\|)',, r'\\\1', htmlTagTxt)   
print (cleanedHtmlTagTxt)

This gives the following output:

ABC -type X \| aas &lt;  ISCO \| ABB \| TTI  &gt; kjhkjh

However, I want to only add a backslash where the '|' character is inside < and > So the first '|' character just after '-type X' should not be changed. Unfortunately, I do not understand the syntax needed to indicate this. Can someone explain how to do this and a bit of the logic behind it ?

1 Answers

IIUC, you could use a combination of html escape and regex escape:

from html import escape
import re

someTxt = "ABC -type X | aas < ISCO | ABB | TTI > kjhkjh"


def replacement(match):
    """This function escapes every | inside the string"""
    return re.sub(r"\|", re.escape("|"), match.group())


# change the text inside < and > using replacement
newText = re.sub(r"<.*?>", replacement, someTxt)

# use html escape to convert < > to &lt; &gt;
result = escape(newText)
print(result)

Output

ABC -type X | aas &lt; ISCO \| ABB \| TTI &gt; kjhkjh
Related