Regex: Remove empty-element tags for xml

regex, xml

Solution

None of those solutions will accommodate attributes like foo="/>". Try:

s:<([\w\-_]+)((?:[^'">]|'[^']*'|"[^"]*")*)/\s*>:<$1$2></$1>:

Exploded to show detail:

<
    ([\w\-_]+)    # tag name
    (
        [^'">]*| # "normal" characters, or
        '[^']*'| # single-quoted string, or
        "[^"]*"  # double-quotes string
    )*
    /\s*         # self-closing
>

This should always work provided that the markup is valid. (You could rearrange this using lazy quantifiers if you so chose; e.g. '[^']' => '.*?'.)

Problem

I'd like to replace all self-closed elements to the long syntax (because my web-browser is tripping on them). Example ``` <iframe src="http://example.com/thing"/> ``` becomes ``` <iframe src="http://example.com/thing"></iframe> ``` I'm using python's flavor of regex.

Original source