繁体   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