我试图在C #中做一个替换正则表达式。我试图用UTF-8中的法线空间替换某些unicode字符(空格)的方法。
让我用密码来解释。我不擅长编写正则表达式、区域性信息和regex。
//This method replace white spaces in unicode by whitespaces UTF-8
public static string cleanUnicodeSpaces(string value)
{
//This first pattern works but, remove other special characteres
//For example: mark accents
//string pattern = @"[^\u0000-\u007F]+";
string cleaned = "";
string pattern = @"[^\u0020\u0009\u000D]+"; //Unicode characters
string replacement = ""; //Replace by UTF-8 space
Regex regex = new Regex(pattern);
cleaned = regex.Replace(value, replacement).Trim(); //Trim by quit spaces
return cleaned;
}
Unicode空间
我做错什么了?
源
解决方案感谢@wiktor-stribiżew和@mathias-r-jessen,解决方案:
string pattern = @"[\u0020\u0009\u000D\u00A0]+";
//I include \u00A0 for replace  
发布于 2017-09-04 21:47:44
regex -- [^\u0020\u0009\u000D]+
--是一个http://www.regular-expressions.info/charclass.html#negated,它匹配除常规空间(\u0020
)、制表符(\u0009
)和回车(\u000D
)之外的任何1+字符。实际上,您正在寻找一个正字符类,它将与您所指示的三个字符中的一个匹配(换行符为\x0A
,回车为\x0D
,选项卡为\x09
)。
你可以用
var res = Regex.Replace(s, @"[\x0A\x0D\x09]", " ");
https://stackoverflow.com/questions/46043891
复制相似问题