2

I have a problem on replacing string using regex, seem I can't get it to work

string = "<font x=''>test</font> <font y=''>test2</font> <font z=''>test3</font>"
if re.search("(<font .*?>)", string, re.IGNORECASE):
    r = re.compile(r"<font (?P<name>.*?)>.*?</font>", re.IGNORECASE)
    string = r.sub(r'', string)

For some reason all the regex deletes the entire string ''. It should return as test test2 test3

2
  • @AvinashRaj Copied wrong code from notepad. Sorry Commented Oct 10, 2014 at 7:43
  • You can directly use re.findall and do this in one step Commented Oct 10, 2014 at 8:00

2 Answers 2

5

Here it is,

>>> import re
>>> string = "<font x=''>test</font> <font y=''>test2</font> <font z=''>test3</font>"
>>> if re.search("(<font .*?>)", string, re.IGNORECASE):
...     r = re.compile(r"</?font.*?>", re.IGNORECASE)
...     string = r.sub(r'', string)
... 
>>> string
'test test2 test3'

DEMO

Pattern Explanation:

  • </?font.*?> This regex would match all the opening and closing font tags. By adding ? after the / will make the previous character that is / as optional.
  • .*? Will do a shortest possible match. ? after the * would force the regex engine to do a shortest possible match because * is greedy by default. It could consume so many chars as much as possible.
  • > Matches the > symbol literally.
  • re.IGNORECASE is called case-insensitive modifier.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Can you explain to me the r = re.compile(r"</?font.*?>", re.IGNORECASE) part please?
So this does multiple searches right? With serchall it does one search. I am using searchall but at the same time I want to replace all whilst still getting the searchall results all in 1 time without loops.
pls ask it as new question.
regex101.com link is very helpful!
1
>([^<]*)<\/

you can use it as

y="<font x=''>test</font> <font y=''>test2</font> <font z=''>test3</font>"
x=re.findall(r"(?<=>)([^<]*)(?=<\/)",y) 
str=" ".join(x)
print str

See demo

http://regex101.com/r/xT7yD8/6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.