首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用regex C#替换空白空间(unicode到utf-8)

如何用regex C#替换空白空间(unicode到utf-8)
EN

Stack Overflow用户
提问于 2017-09-04 20:53:41
回答 1查看 3K关注 0票数 2

我试图在C #中做一个替换正则表达式。我试图用UTF-8中的法线空间替换某些unicode字符(空格)的方法。

让我用密码来解释。我不擅长编写正则表达式、区域性信息和regex。

代码语言:javascript
运行
复制
    //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空间

  • HT:U+0009 =字符制表
  • LF:U+000A =线路馈电
  • CR:U+000D =载运返回

我做错什么了?

  1. Unicode字符:https://unicode-table.com/en
  2. 空白:字符
  3. Regex:https://msdn.microsoft.com/es-es/library/system.text.regularexpressions.regex(v=vs.110).aspx

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

代码语言:javascript
运行
复制
 string pattern = @"[\u0020\u0009\u000D\u00A0]+";
 //I include \u00A0 for replace &nbsp
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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 )。

你可以用

代码语言:javascript
运行
复制
var res = Regex.Replace(s, @"[\x0A\x0D\x09]", " ");

regex演示

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46043891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档