Anonymous
Anonymous

Reputation: 81

Regex: Remove everything except allowed characters. how?

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

Upvotes: 8

Views: 4428

Answers (3)

Christian.K
Christian.K

Reputation: 49290

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();
    }

Upvotes: 0

Scott
Scott

Reputation: 999

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

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039428

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);

Upvotes: 22

Related Questions