[英]How do I remove invisible unicode characters from the beginning and the end of a string?
如何以可靠的方式刪除字符串開頭和結尾的不可見字符? 就我而言,我的字符串以從左到右嵌入[LRE]字符開頭。 但是, string.Trim()
不會將其刪除,如下所示:
var myString = "\u202atest";
myString.Trim();
// Prints:
// "test"
myString.Trim().ToCharArray();
// Prints:
// {char[5]}
// [0]: 8234 ''
// [1]: 116 't'
// [2]: 101 'e'
// [3]: 115 's'
// [4]: 116 't'
.NET Framework API中是否有功能可以修剪所有此類字符? 我認為不止一個,而且我想避免必須手動指定每個。
不可見是不明確的。 一種符合Unicode的解決方案:regex類常規類別 [\\p{Control}\\p{Format}\\p{Nonspacing_Mark}\\p{Enclosing_Mark}\\p{Line_Separator}\\p{Paragraph_Separator}]
字符沒有顯示寬度。 一無所有。
$ length "\x{202a}test" =~ s/[\p{Cc}\p{Cf}\p{Mn}\p{Me}\p{Zl}\p{Zp}]//r
4
在C#中:
public static string RemoveCharactersWithoutDisplayWidth(this string str)
{
var regex = new Regex(@"[\p{Cc}\p{Cf}\p{Mn}\p{Me}\p{Zl}\p{Zp}]");
return regex.Replace(str, "");
}
你可以試試:
mystring = myString.Trim('\u202a');
如果要修剪更多類似的字符,可以將這些字符定義為數組。
char[] trimChars = {'\u202a','\u202b'};//More chars as your wish
mystring = myString.Trim(trimChars);
您可以嘗試分析字節:
var s = "\u202atest";
string s2 = null;
byte[] bytes = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, bytes, 0, bytes.Length);
if (bytes[0] == 0x2a && bytes[1] == 0x20)
{
char[] c = new char[(bytes.Length - 2) / sizeof(char)];
Buffer.BlockCopy(bytes, 2, c, 0, bytes.Length - 2);
s2 = new string(c);
}
var c2 = s2.ToCharArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.