我正在使用此处找到的 HTML 清理白名单代码:
http://refactormycode.com/codes/333-sanitize-html
我需要添加“字体”标签作为附加标签进行匹配,因此我尝试在 <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);
}
}
除上述情况外,我的代码与我链接到的页面中的代码几乎相同。当我尝试在 C# 中对此进行测试时,它会抛出一个异常,提示“Not enough )'s
”。我数了几次括号,并通过几个在线的基于 Javascript 的正则表达式测试器运行表达式,但似乎没有一个告诉我任何问题。
我是否在正则表达式中遗漏了导致括号转义的内容?我需要做什么来解决这个问题?
更新
经过大量的反复试验,我记得 #
sign 是正则表达式中的注释。解决这个问题的关键是转义 #
特点。以防其他人遇到同样的问题,我已经包含了我的修复程序(只是转义了 #
标志)
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);
}
}
最佳答案
您的 IsMatch 方法使用选项 RegexOptions.IgnorePatternWhitespace
,它允许您将注释放在正则表达式中,因此您必须转义 # 字符,否则它将被解释为注释。
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);
}
关于c# - 为什么在这个 Regex 中要转义左括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/240098/