If I have string such as 'xktzMnTdMaaM", how to remove everything except 'M' and 'T' - so the resulting string is 'MTMM' ? Thanks in advance.
In regex, the uppercase metacharacter is always the inverse of the lowercase counterpart. \d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).
Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.
To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With