2017-06-12 103 views
1

如何保留字母,數字,符號和重音字符c#。我想擺脫表情符號和「最高」字符。這可行,但它忽略了新行。如何保留重音字符,字母數字和符號

string Message = @"The cédille (cedilla) Ç ...The Accent aigu (acute accent) é ... 
     The Accent circonflexe (circumflex) â, ê, î, ô, û ... 
     The accent grave (grave accent) à, è, ù ... 
     The accent tréma (dieresis/umlaut) ë, ï, ü" 最高 ; 

var msg = Regex.Match(Message, @"[a-zA-zÀ-ÿ0-9/ [.,\/#!$%\^&\*;:{}=\-_`~()?<>]+"); 

Console.WriteLine(msg); 
Console.ReadKey(); 
+0

通過使用不同的'Encoding'可能 – Rahul

+0

的要求還不太清楚。你需要匹配什麼類型的字母?我懷疑你想匹配所有的ASCII字符和所有的拉丁語 - [[\ x00- \ x7F \ p {IsLatin-1Supplement} \ p {IsLatinExtended-A} \ p {IsLatinExtended-B} \ p {IsLatinExtendedAdditional}] +'? –

回答

2

在我看來,你只想保留ASCII字符,而不是所有其他字符集(如UTF-8/16)字符。

這會做:

string msg = new string(Message.Where(c => ((int)c) < 256).ToArray()); 
+1

某些Unicode字符(Emojis)由多個字符組成,其中一個字符可以匹配'(int)c)<256',例如'string msg = new string(「*️⃣#️⃣*️⃣」.Where(c =>((int)c)<256).ToArray());' – fubo

+0

@fubo不錯的接收。我不知道如何解決這個問題,除了走下角色並根據UTF-8文檔檢查它們。也許這樣可能會有幫助? https://stackoverflow.com/q/23940623/993547 –

+1

所有鍵帽字符都符合該條件 - 不知道如何解決這個問題,只是想指出:http://unicode.org/emoji/charts/full-emoji -list.html#鍵帽 – fubo

0

使用Matches方法

var matches = Regex.Matches(Message, @"[a-zA-zÀ-ÿ0-9/ [.,\/#!$%\^&\*;:{}=\-_`~()?<>]+"); 
foreach (Match match in matches) 
{ 
    Console.WriteLine(match.Value); 
} 

,將返回你MatchCollection,你可以很容易地轉換成字符串換行符。

string message = ""; 
foreach (Match match in matches) 
{ 
    message += match.Value + Environment.NewLine; 
} 

Console.WriteLine(message); 
相關問題