This RegEx is very specific but demonstrates a technique to find and modify HTML tags.
Finds <td> and <th> tags that:
- Do not already have padding.
- Are complete (i.e. have a closing tag)
- Are not empty (nor contain only one <br> tag)
and add styling to it to give it a padding of 3 pixels between the table cells' borders and their contents.
In order to be more readable, it uses named capture groups.
- Tag:
th
or td
- NonStyleAttributes1: Substring of HTML tag attributes, if any, that are before the style attribute.
- SpaceBeforeStyle: If contiguous whitespace characters immediately before the style attribute, this is all but the last whitespace character.
- OtherStyling: style attribute value string that doesn't contain "padding" (and ends with a semi-colon)
- NonStyleAttributes2: Substring of HTML tag attributes, if any, that are after the style attribute.
- TagEnd: Anything between the last attribute and the end of the opening tag, including the ending
>
.
If it finds a match so far, it looks ahead to ensure there's anything between this opening tag and the closing tag besides a simple <br>
tag.
If all that is matched then we have everything we need to replace the opening tag with an opening tag that contains padding by assembling the following...
<
- Tag (th or td)
- NonStyleAttributes1 - attributes before the style tag, if any
- SpaceBeforeStyle - any extra white-space before the style tag
style="padding: 3px;
- OtherStyling - any existing styling
"
- NonStyleAttributes2 - attributes after the style attribute, if any
- TagEnd - the ending of the opening tag (any white-space and
>
)