0

I want python regular expression to replace & with & in xml obj. But not replace < or >

Example:

dataobj = '<Style width="100.000000%"/><Data&><![CDATA[<p>TEST TEST &lt; TEST 10&gt; starts &" and T&L'

And my expected output should be

outputdata = '<Style width="100.000000%"/><Data&amp;><![CDATA[<p>TEST TEST &lt; TEST 10&gt; starts &amp;" and T&amp;L'

I can strictly say for &lt; &gt; &eq; &in; &amp; should not change anything. where ever i found & should replace with &amp; but not for &lt; &gt; &eq; &in; &amp;

3

1 Answer 1

0

I think a negative lookahead might be sufficient, although depending on the exact use case an XML parser may be better:

import re
dataobj = '<Style width="100.000000%"/><Data&><![CDATA[<p>TEST TEST &lt; TEST 10&gt; starts &" and T&L'

amp = re.compile(r'&(?![lg]t;)')
print(re.sub(amp,'&amp;',dataobj))

produces

<Style width="100.000000%"/><Data&amp;><![CDATA[<p>TEST TEST &lt; TEST 10&gt; starts &amp;" and T&amp;L

Not the answer you're looking for? Browse other questions tagged or ask your own question.