这里的问题是您尝试将 Regex.Unescape 应用于未完全使用 Regex.Escape 处理的内容。几乎任何对消息进行部分编码而其他部分未编码的编码都会遇到同样的问题。您可以尝试预测所有的变化,但在某些情况下,您将无法区分打算未编码的内容和其他未转义的内容。唯一可靠的方法是确保对整个消息进行一致编码。这意味着在您对字符串执行操作时完全解码消息,然后重新编码整个字符串。
这是我在 linqpad 中进行的演示,每个对应的.Dump() 都有输出。它进行完整编码,然后完成解码。当正则表达式编码时,您会注意到 \w 在中途被转义。 因此,您遇到的问题的症结在于消息的“某些消息 \w+ here”部分不是正则表达式编码的,因此将 Regex.Unescape 应用于它将会失败,因为您无法取消转义某些内容没有逃脱。
string ori = @"<div>some message \w+ here</div>"; //only escaping is \\ for the C# string which is really \
ori.Dump(); // Verify that real string is "<div>some message \w+ here</div>"
string regexEscaped = System.Text.RegularExpressions.Regex.Escape(ori);
regexEscaped.Dump();
//Regex escape does not replace "<" with unicode characters as it seems an unnecesary escape sequence. I can force them into the regex encoded string
//This step is unnecesary and can be commented out.
//regexEscaped = regexEscaped.Replace(">", @"\u003e").Replace("<",@"\u003c");
//regexEscaped.Dump();
string htmlEscaped_regexEscaped = System.Web.HttpUtility.HtmlEncode(regexEscaped).Dump();
System.Text.RegularExpressions.Regex.Unescape( System.Web.HttpUtility.HtmlDecode(htmlEscaped_regexEscaped)).Dump();
// Since we encoded the entire string we were able to successfully decode it.
输出:
Original: <div>some message \w+ here</div>
Rgx Escpd: <div>some\ message\ \\w\+\ here</div>
HTML Encd: <div>some\ message\ \\w\+\ here</div>
HTML Uncd & Rgx Unesc: <div>some message \w+ here</div>
你是用这个来匹配的吗?
如果您的意图是使用字符串“\u003cdiv\u003esome message \w+ come here\u003c/div\u003e”作为正则表达式来执行匹配,则无需对其执行任何操作。实现完整正则表达式功能集的匹配器应该理解“\u003c”,因此无需尝试将其转换为“
http://www.regular-expressions.info/unicode.html
客户端并没有真正进行 Regex Escape?
似乎客户端并没有真正进行正则表达式转义,因此 Regex.Unescape 肯定会失败。它是否在进行某种 Html 编码,但用 unicode 代码而不是 HTML 字符代码替换字符?也许。在没有记录客户行为的情况下,这是一个有根据的猜测,希望他们以后不会产生其他不一致的编码。
在这种情况下,我将只针对 unicode 转义序列。这是一个涵盖替换 unicode 转义序列和不使用 Regex.Unescape 主题的问题:
How do convert unicode escape sequences to unicode characters in a .NET string