2

I'm trying to change a string that contains substrings such as

the</span></p>
<p><span class=font7>currency

to

the currency

At the line break is CRLF

The words before and after the code change. I only want to replace if the second word starts with a lower case letter. The only thing that changes in the code is the digit after 'font'

I tried:

p = re.compile('</span></p>\r\n<p><span class=font\d>([a-z])')
res = p.sub(' \1', data)

but this isn't working

How should I fix this?

8
  • 1
    because regex shouldn't be used to parse html. Commented Oct 15, 2011 at 23:46
  • In addition to @JBernardo your question is unclear. Such as? So what else? Commented Oct 15, 2011 at 23:48
  • @FailedDev: does the edit clarify? Commented Oct 15, 2011 at 23:51
  • @JBernardo: what would you suggest, especially to replace only if the second word starts with a lower case letter? Commented Oct 15, 2011 at 23:56
  • How about putting python strip html into the search box and pressing enter? The first hit will get you this nifty anser. Commented Oct 16, 2011 at 0:05

3 Answers 3

1

Use a lookahead assertion.

p = re.compile('</span></p>\r\n<p><span class=font\d>(?=[a-z])')
res = p.sub(' ', data)
Sign up to request clarification or add additional context in comments.

2 Comments

That does not seem to find the substring. p.match(data) returns nothing
@foosion: match searches from the start of the string. Try p.search(data).
1

I think you should use the flag re.DOTALL, which means it will "see" nonprintable characters, such as linebreaks, as if they were regular characters.

So, first line of your code would become :

p = re.compile('</span></p>..<p><span class=font\d>([a-z])', re.DOTALL)

(not the two unescaped dots instead of the linebreak).

Actually, there is also re.MULTILINE, everytime I have a problem like this one of those end up solving the problem.

Hope it helps.

1 Comment

That does not seem to find the substring. p.match(data) returns nothing.
1

This :

result = re.sub("(?si)(.*?)</?[A-Z][A-Z0-9]*[^>]*>.*</?[A-Z][A-Z0-9]*[^>]*>(.*)", r"\1 \2", subject)

Applied to :

the</span></p>
<p><span class=font7>currency

Produces :

the currency

Although I would strongly suggest against using regex with xml/html/xhtml. THis generic regex will remove all elements and capture any text before / after to groups 1,2.

2 Comments

The reason the html seems reversed is that you're seeing the end of one paragraph and the beginning of another. That regex seems very complex
@foosion Well this regex will work regardless of any elements you throw in it.

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.