簡體   English   中英

使用C#中的Regex從字符串中刪除無效字符

[英]Remove invalid characters from string using Regex in C#

我找到了關於該主題的幾篇文章,但提到的解決方案在我的情況下不起作用。

考慮以下代碼:

    static void Main(string[] args)
    {
        string rgs = "^[ -~]*(?:\r?\n[ -~]*)*$";

        string TestStrNoMatch = "One\tTwo\r\nThree Ö";
        string TestStrMatch = "OneTwo\r\nThree ";

        Regex rgx = new Regex(rgs);

        bool Match = rgx.IsMatch(TestStrNoMatch); // false

        Match = rgx.IsMatch(TestStrMatch); // true

        string result = Regex.Replace(TestStrNoMatch, rgs, "");

        // result is the same as TestStrNoMatch
    }

預期的結果是\\ t和Ö被刪除,但這沒有發生。 結果的值與TestStrNoMatch完全相同

澄清 :我在示例中使用的正則表達式僅允許在空格和〜之間的字符(英文字母,數字和某些特殊字符)以及Windows和Unix格式的換行符。 我想刪除其他所有內容。

您的正則表達式需要與要刪除的字符匹配,以使regex.replace起作用。 由於您的模式不匹配任何內容,因此不會替換任何內容。 尚不清楚您要刪除的內容,但這是一個示例:

模式(\\\\t)|(Ö)與制表符和Ö字符匹配,因此

    string sample = "ab\tcefÖ";
    string pattern = "(\\t)|(Ö)";
    string result = Regex.Replace(sample, pattern, "");
    System.Console.WriteLine("SAMPLE : " + sample);
    System.Console.WriteLine("RESULT : " + result);

結果是

SAMPLE: ab      cefÖ
RESULT: abcef

如果您解釋了要刪除的所有內容,那么我可以為您提供更具代表性的正則表達式模式。 例如,要刪除空格和〜之間的所有字符以及制表符,可以使用[^ -~]|(\\\\t)

為什么不這樣做而不是使用Regex? 我認為更好的可讀性。

string text = "abcdef";
char[] invalidChars = { 'a', 'b', 'c' }; // Your invalid characters here

if (text.IndexOfAny(invalidChars) != -1)
{
    text = new String(text.Where(c => !invalidChars.Contains(c)).ToArray());
}

輸出:“ def”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM