Mar*_*ijn 3 c# regex string sanitization
问题
我需要清理从用户输入到有效属性名称的字符串集合。
语境
We have a DataGrid that works with runtime generated classes. These classes are generated based on some parameters. Parameter names are converted into Properties. Some of these parameter names are from user input. We implemented this and it all seemed to work great. Our logic to sanitizing strings was to only allow numbers and letters and convert the rest to an X.
const string regexPattern = @"[^a-zA-Z0-9]";
return ("X" + Regex.Replace(input, regexPattern, "X")); //prefix with X in case the name starts with a number
Run Code Online (Sandbox Code Playgroud)
The property names were always correct and we stored the original string in a dictionary so we could still show a user friendly parameter name.
However, where the trouble starts is when a string only differs in illegal characters like this:
Parameter Name
Parameter_Name
These were both converted into:
ParameterXName
一种解决方案是只生成一些安全的,不相关的名称,例如A,BC等。但是我希望该名称在调试中仍然可以识别。除非太复杂以至于无法实现这种行为。
我在StackOverflow上查看了其他问题,但它们似乎都删除了非法字符,这具有相同的问题。
我觉得自己正在重新发明轮子。有一些标准的解决方案或技巧吗?
我可以建议更改生成安全,不相关和可识别名称的算法。
在c#_中,成员名称的有效符号。替换所有无效的符号(chr)不是X,但用"_"+(short)chr+"_"。
public class Program
{
public static void Main()
{
string [] props = {"Parameter Name", "Parameter_Name"};
var validNames = props.Select(s=>Sanitize(s)).ToList();
Console.WriteLine(String.Join(Environment.NewLine, validNames));
}
private static string Sanitize(string s)
{
return String.Join("", s.AsEnumerable()
.Select(chr => Char.IsLetter(chr) || Char.IsDigit(chr)
? chr.ToString() // valid symbol
: "_"+(short)chr+"_") // numeric code for invalid symbol
);
}
}
Run Code Online (Sandbox Code Playgroud)
版画
Parameter_32_Name
Parameter_95_Name
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1921 次 |
| 最近记录: |