-1

I have a string like below:

string = "<sub>1</sub>"

I wanna change the tag sub to something like this:

 "<sub>1</sub>" ->  "-sub--1--sub-"

I've tried this:

string1 = re.sub('<sub.*>','-sub--',string)
string1 = re.sub('</sub>','--sub-',string)

but it doesn't work.

smottt
  • 3,272
  • 11
  • 37
  • 44
mazouu rahim
  • 113
  • 1
  • 2
  • 8

2 Answers2

2
re.sub(r"<([^>]*)>([^<]*)<\/([^>]*)>", r"-\1--\2--\3-", string)
Mayur Koshti
  • 1,794
  • 15
  • 20
0

You've used the greedy operator .*, where the non-greedy operator .*? would work better. Additionally, your second change overrides your first. Try this:

string1 = re.sub('<sub.*?>','-sub--',string)
string1 = re.sub('</sub>','--sub-',string1)

However, you should probably avoid using regex to parse XML. Use an XML parser instead.

Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308