我正在使用此处的HTML清理白名单代码:http:
//refactormycode.com/codes/333-sanitize-html
我需要添加"font"标记作为匹配的附加标记,因此我尝试在<img标记检查 后添加此条件
if (tagname.StartsWith("<font"))
{
// detailed <font> tag checking
// Non-escaped expression (for testing in a Regex editor app)
// ^<font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?>$
if (!IsMatch(tagname, @"<font
(\s*size=""\d{1}"")?
(\s*color=""((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)"")?
(\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")?
\s*?>"))
{
html = html.Remove(tag.Index, tag.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
除了上面的条件,我的代码几乎与我链接到的页面中的代码相同.当我尝试在C#中测试它时,它会抛出一个异常说" Not enough )'s".我已经多次计算了括号,我通过几个基于Javascript的在线正则表达式测试程序运行表达式,但它们似乎都没有告诉我任何问题.
我在我的正则表达式中遗漏了导致括号逃脱的内容吗?我需要做些什么来解决这个问题?
更新
经过大量的反复试验,我记得这个#标志是正则表达式中的评论.解决这个问题的关键是逃避#角色.万一其他人遇到同样的问题,我已经包括我的修复(只是逃避#标志)
if (tagname.StartsWith("<font"))
{
// detailed <font> tag checking
// Non-escaped expression (for testing in a Regex editor app)
// ^<font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?>$
if (!IsMatch(tagname, @"<font
(\s*size=""\d{1}"")?
(\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")?
(\s*face=""(Arial|Courier\sNew|Garamond|Georgia|Tahoma|Verdana)"")?
\s*?>"))
{
html = html.Remove(tag.Index, tag.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
您的IsMatch方法正在使用该选项RegexOptions.IgnorePatternWhitespace,允许您将注释放在正则表达式中,因此您必须使用#chatacter,否则它将被解释为注释.
if (!IsMatch(tagname,@"<font(\s*size=""\d{1}"")?
(\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")?
(\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")?
\s?>"))
{
html = html.Remove(tag.Index, tag.Length);
}
Run Code Online (Sandbox Code Playgroud)