使用CFML正则移除带任意属性的<FONT>及闭合标签
Got it, let's sort out your regex problem! Your current attempt only catches the start of opening <FONT> tags, but misses the full tag (including attributes and closing >) and all the </FONT> closing tags entirely. Here's how to fix it:
The Correct Regex
We need to match two distinct patterns to cover all cases:
- Any opening
<FONT>tag with any attributes and values (no matter how complex) - Any closing
</FONT>tag
Since HTML tags are case-insensitive (e.g., <font> or <Font> should also be removed), we'll add a case-insensitive modifier to make the regex robust.
Regex Pattern:
(?i)<FONT[^>]*>|</FONT>
Breakdown of the Pattern:
(?i): Enables case-insensitive matching (catches<font>,<Font>,<FONT>, etc.)<FONT[^>]*>: Matches the full opening tag:<FONT: Starts with the opening tag name[^>]*: Matches any character except>(this covers all attributes and their values, no matter how long or complex)>: Ends the opening tag
|: Acts as an OR operator to match either the opening tag or the closing tag</FONT>: Matches the exact closing tag (the(?i)modifier makes this case-insensitive too)
ColdFusion Code Implementation
Since you're using ColdFusion's rereplace function, here's the working code:
loc.result = rereplace(arguments.htmlString, "(?i)<FONT[^*\\>]", "", "ALL");
- The
"ALL"flag ensures all occurrences are replaced (not just the first one) - The
(?i)modifier inside the regex handles case insensitivity for tag names, so it works regardless of how the tags are capitalized
Testing With Your Example Input
Let's apply this to your sample HTML snippet:
Original Input:
<LI><FONT size=2 face=Verdana><FONT size=2 face=Verdana><STRONG>random text</STRONG></FONT></LI>
After Replacement:
<LI><STRONG>random text</STRONG></LI>
This correctly removes both nested opening <FONT> tags and the closing </FONT> tag, matching your desired output perfectly.
Why Your Original Regex Failed
Your original pattern \\<FONT[^*\\> had two critical issues:
- The character set
[^*\\>was incorrectly defined — you meant to match everything up to the closing>, which should be[^>]*(match any character except>zero or more times) - It didn't include a pattern to match the closing
</FONT>tags at all
内容的提问来源于stack exchange,提问作者Phillip Pantaleano

