【发布时间】:2019-11-25 11:21:36
【问题描述】:
在将数据写入日志文件之前,我正在使用以下规则编写字符串清理程序:
- 指定的字符被列入白名单(
A-Za-z0-9以及<>[],.:_-和空格) - 指定的字符在三角括号内被转换成英文版本的名字(例如
"," => "<comma>"、"%" => "<percent>") - 任何其他内容都将转换为其在三角括号内的 unicode 编号(例如
"φ" => "<U+03C6>"、"π" => "<U+03C0>")
到目前为止 1 和 2 都在工作,但不是 3。这是我目前所拥有的:
public static string Safe(string s)
{
s = s
.Replace("<", "ooopen-angle-brackettt") // must come first
.Replace(">", "ccclose-angle-brackettt") // must come first
//.Replace(",", "<comma>") // allow
//.Replace(".", "<dot>") // allow
//.Replace(":", "<colon>") // allow
.Replace(";", "<semi-colon>")
.Replace("{", "<open-curly-bracket>")
.Replace("}", "<close-curly-bracket>")
//.Replace("[", "<open-square-bracket>") // allow
//.Replace("]", "<close-square-bracket>") // allow
.Replace("(", "<open-bracket>")
.Replace(")", "<close-bracket>")
.Replace("!", "<exclamation-mark>")
.Replace("@", "<at>")
.Replace("#", "<hash>")
.Replace("$", "<dollar>")
.Replace("%", "<percent>")
.Replace("^", "<hat>")
.Replace("&", "<and>")
.Replace("*", "<asterisk>")
//.Replace("-", "<dash>") // allow
//.Replace("_", "<underscore>") // allow
.Replace("+", "<plus>")
.Replace("=", "<equals>")
.Replace("\\", "<forward-slash>")
.Replace("\"", "<double-quote>")
.Replace("'", "<single-quote>")
.Replace("/", "<forward-slash>")
.Replace("?", "<question-mark>")
.Replace("|", "<pipe>")
.Replace("~", "<tilde>")
.Replace("`", "<backtick>")
.Replace("ooopen-angle-brackettt", "<open-angle-bracket>")
.Replace("ccclose-angle-brackettt", "<close-angle-bracket>");
// all working upto here. broken below:
Regex itemRegex = new Regex(@"[^A-Za-z0-9<>[\]:.,_\s-]", RegexOptions.Compiled);
foreach (Match itemMatch in itemRegex.Matches(s))
{
// the reason for [0] and [1] is that I read that unicode consists of 2 characters
s = s.Replace(
itemMatch.ToString(),
"<U+" +
(((int)(itemMatch.ToString()).ToCharArray()[0]).ToString("X4")).ToString() +
(((int)(itemMatch.ToString()).ToCharArray()[1]).ToString("X4")).ToString() +
">"
);
}
return s;
}
正则表达式部分未捕获输入字符串中的 unicode 字符。我该如何解决这个问题
【问题讨论】:
-
你应该转义
],[^A-Za-z0-9<>[\]:.,_\s-],{1}是多余的,去掉它。 -
@WiktorStribiżew 谢谢我会更新这个问题。请注意,这并不能解决问题。
-
你说“不捕获unicode字符”,你能提供一个测试用例吗?我认为您正在处理表情符号。
-
@WiktorStribiżew 请按照问题的第 3 部分使用 φ 和 π
-
所有这些卫生设施的目的是什么?非 ASCII 字符有什么不安全的地方?为什么不写 UTF-8 日志文件?
标签: c# regex unicode-string