0

I'm using Python re library. No beautifulsoup4 here.

I have:

<div class="col-xs-12">100/25</div>

I want:

<div class="column-md">100/25</div>

What I need is to select col-xs-12 ONLY if inside a <div class=""> and replace it.

So far I have:

text.replace("<class>(.|\n)col-xs-12<\/class>, "column-md")

But it doesn't work.

3
  • You should use beautifulsoup. Regular expressions are not adapted to parse html efficiently. Commented Mar 14, 2020 at 4:34
  • I don't need to parse html. It's more about find and replace a text file. Commented Mar 14, 2020 at 4:36
  • I need to understand something: you mean, in your file you do not have ONLY HTML ? You should use regex only if HTML and plain text are mixed in your file. Otherwise, the most appropriate way to handle this is the Python LibXML library, namely attribute updating. Commented Mar 14, 2020 at 6:49

1 Answer 1

1

Try using re.sub with a callback function:

def replace_div(m):
    return re.sub(r'\bclass="col-xs-12"', 'class="column-md"', m.group(0))

inp = 'blah <b>stuff</b> blah <div class="col-xs-12">100/25</div> more blah'
out = re.sub(r'<div[^>]*\bclass="col-xs-12"[^>]*>.*?</div>', replace_div, inp)
print(inp)
print(out)

This prints:

blah <b>stuff</b> blah <div class="col-xs-12">100/25</div> more blah
blah <b>stuff</b> blah <div class="column-md">100/25</div> more blah

The strategy here is to first match all <div> tags containing the appropriate class attribute. Then, we pass such matches to a callback function which then does the class replacement.

Note that in general using regex on nested content like HTML is not recommended. But, sometimes we are forced to manipulate such content using a text editor.

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting. 1) it doesn't work if there is more than one class (see the comment below plz) 2) Is this the way to extend it to replace other classes return re.sub(r'\bclass="align-right"', 'class="column-right"', m.group(1)) ?
1) It does work if there be more than one class. The only requirement is that the class you want to target be present. 2) I don't understand what you are asking.
2) how to extend the function, so I can select more classes.

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.