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();
}
精彩评论