开发者

Regex: Remove everything except allowed characters. how?

开发者 https://www.devze.com 2023-04-02 02:26 出处:网络
If I have string such as \'xktzMnTdMaaM\", how to remove everything except \'M\' and \'T\' - so the开发者_Go百科 resulting string is \'MTMM\' ? Thanks in advance.var input = \"xktzMnTdMaaM\";

If I have string such as 'xktzMnTdMaaM", how to remove everything except 'M' and 'T' - so the开发者_Go百科 resulting string is 'MTMM' ? Thanks in advance.


var input = "xktzMnTdMaaM";
var output = Regex.Replace(input, "[^MT]", string.Empty);

and if you wanted to be case insensitive:

var output = Regex.Replace(input, "[^mt]", string.Empty, RegexOptions.IgnoreCase);


To add to Darin's answer, you could solve this differently using LINQ if you wanted:

string.Concat("xktzMnTdMaaM".Where(c => "MT".Contains(c)))


From your problem description using regular expressions sound pretty much overkill. You could just roll a manual solution like so:

    public static string RemoveNonMTChars(string str)
    {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] == 'M' && str[i] == 'T')
            {
                sb.Append(str[i]);
            }
        }

        return sb.ToString();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消