Die*_*mos 6 c# regex validation trim
我正在从.csv文件中大量上传信息,我需要将此字符替换为ascii"�"以获取正常空间"".
对于C/C++/JAVA,字符"�"对应于"\ uFFFD",它似乎称为REPLACEMENT CHARACTER.其他如C#官方文档中的空格类型如U + FEFF,205F,200B,180E,202F.
我正在尝试以这种方式替换
public string Errors="";
public void test(){
string textFromCsvCell= "";
string validCharacters="^[0-9A-Za-z().:%-/ ]+$";
textFromCsvCell="This is my text from csv file"; //ALl spaces aren't normal space " "
string cleaned = textFromCsvCell.Replace("\uFFFD", "\"")
if (Regex.IsMatch(cleaned, validCharacters ))
//All code for insert
else
Errors=cleaned;
//print Errors
}
Run Code Online (Sandbox Code Playgroud)
测试方法给我看这个文字:
"这是来自csv文件的my�texto"
我尝试了一些解决方案
尝试解决方案1:使用修剪
Regex.Replace(value.Trim(), @"[^\S\r\n]+", " ");
Run Code Online (Sandbox Code Playgroud)
尝试解决方案2:使用替换
System.Text.RegularExpressions.Regex.Replace(str,@"\s+"," ");
Run Code Online (Sandbox Code Playgroud)
尝试解决方案3:使用修剪
String.Trim(new char[]{'\uFEFF','\u200B'});
Run Code Online (Sandbox Code Playgroud)
尝试解决方案4:将[\ S\r \n]添加到validCharacters
string validCharacters="^[\S\r\n0-9A-Za-z().:%-/ ]+$";
Run Code Online (Sandbox Code Playgroud)
什么都行不通
有人有想法吗?我怎样才能更换它?我非常感谢你的帮助,谢谢
资料来源:
http://www.fileformat.info/info/unicode/char/0fffd/index.htm
这是原始字符串:
"监测葡萄糖的持续性系统"
在0x ...表示法
葡萄糖的持续系统.0xA0MONITORING CONTINUES
转到这里,Unicode代码转换器:http://r12a.github.io/apps/conversion/ 查看转换并执行替换
就我而言,我做了一个简单的替换:
string value = "SYSTEM OF MONITORING CONTINUES OF GLUCOSE";
//value containt non-breaking whitespace
//value is "SYSTEM OF�MONITORING CONTINUES OF GLUCOSE"
string cleaned = "";
string pattern = @"[^\u0000-\u007F]+";
string replacement = " ";
Regex rgx = new Regex(pattern);
cleaned = rgx.Replace(value, replacement);
if (Regex.IsMatch(cleaned,"^[0-9A-Za-z().:<>%-/ ]+$"){
//all code for insert
else
//Errors message
Run Code Online (Sandbox Code Playgroud)
此表达式表示所有可能的空格:空格,制表符,分页符,换行符和回车符
[ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000]
Run Code Online (Sandbox Code Playgroud)
参考资料 https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
使用字符串替换:
\n使用一个简单的String.Replace()
.
我假设您想要删除的唯一字符是您在问题中提到的字符:\xc3\xaf\xc2\xbf\xc2\xbd
并且您想用普通空格替换它们。
string text = "imp\xc3\xaf\xc2\xbf\xc2\xbdortant";\nstring cleaned = text.Replace(\'\\u00ef\', \' \')\n .Replace(\'\\u00bf\', \' \')\n .Replace(\'\\u00bd\', \' \');\n// Returns \'imp ortant\'\n
Run Code Online (Sandbox Code Playgroud)\n或者使用 Regex.Replace:
\nstring cleaned = Regex.Replace(text, "[\\u00ef\\u00bf\\u00bd]", " ");\n// Returns \'imp ortant\'\n
Run Code Online (Sandbox Code Playgroud)\n尝试一下:Dotnet Fiddle
\n 归档时间: |
|
查看次数: |
5945 次 |
最近记录: |