如何用正则表达式C#替换空格(将Unicode转换为utf-8)

Die*_*mos 2 c# regex unicode replace

我正在尝试在C#中执行替换正则表达式。我尝试编写的方法用UTF-8中的普通空格替换了一些Unicode字符(空格)。

让我用代码解释。我不好写正则表达式,文化信息和正则表达式。

    //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;
    }
Run Code Online (Sandbox Code Playgroud)

Unicode空格

  • HT:U + 0009 =字符列表
  • LF:U + 000A =换行
  • CR:U + 000D =回车

我做错了什么?

资源

  1. Unicode字符:https//unicode-table.com/en
  2. 空白:https//en.wikipedia.org/wiki/Whitespace_character
  3. 正则表达式:https ://msdn.microsoft.com/es-es/library/system.text.regularexpressions.regex( v= vs.110).aspx

解决方案 感谢@ wiktor-stribi?ew和@ mathias-r-jessen,解决方案:

 string pattern = @"[\u0020\u0009\u000D\u00A0]+";
 //I include \u00A0 for replace &nbsp
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 5

您的正则表达式- [^\u0020\u0009\u000D]+是一个否定的字符类,与常规空格(),制表符()和回车符()以外的任何1个以上的字符匹配。您实际上是在寻找一个正字符类,该类与您在问题中指定的三个字符之一(换行符,回车符和制表符)相匹配,并带有常规空格()。\u0020\u0009\u000D\x0A\x0D\x09\x20

你可以只用

var res = Regex.Replace(s, @"[\x0A\x0D\x09]", " ");
Run Code Online (Sandbox Code Playgroud)

正则表达式演示