开发者

Regex: Remove everything except allowed characters. how?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜