[英]How to remove non-ASCII word from a string in C#
我想過濾一些有一些錯誤字母的字符串(非ASCII )。 它在Notepad,Visual Studio 2010和MySQL中看起來有所不同。
如何檢查字符串是否包含非ASCII字母以及如何刪除它們?
您可以使用正則表達式過濾非ASCII字符:
string input = "AB £ CD";
string result = Regex.Replace(input, "[^\x0d\x0a\x20-\x7e\t]", "");
您可以使用正則表達式。
Regex.Replace(input, "[^a-zA-Z0-9]+", "")
您還可以使用\\W+
作為模式來刪除任何非字符。
這是一個神派:
Regex.Replace(input, @"[^\u0000-\u007F]", "");
我想我最初在其他地方得到了它,但這里是相同答案的鏈接:
首先,您需要確定“單詞”的含義。 如果不是ascii,這可能意味着非英語?
就個人而言,我會問你為什么需要這樣做以及你的應用程序與數據沖突的基本假設是什么? 根據具體情況,我建議您重新編碼來自源編碼的文本,盡管這將是一個有損轉換,或者,可以解決這個基本假設,以便您的應用程序正確處理數據。
我覺得這個簡單的東西可能會起作用,不是嗎?
public static string AsciiOnly(this string input, bool includeExtendedAscii)
{
int upperLimit = includeExtendedAscii ? 255 : 127;
char[] asciiChars = input.Where(c => (int)c <= upperLimit).ToArray();
return new string(asciiChars);
}
用法示例:
string input = "AB£ȼCD";
string asciiOnly = input.AsciiOnly(false); // returns "ABCD"
string extendedAsciiOnly = input.AsciiOnly(true); // returns "AB£CD"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.