Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Remove everything except allowed characters. how?

Tags:

c#

regex

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

like image 389
Anonymous Avatar asked Sep 04 '11 12:09

Anonymous


People also ask

What does \d mean in regex?

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] ).

What does \+ mean in regex?

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.

How do you match a character except one regex?

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


1 Answers

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);
like image 85
Darin Dimitrov Avatar answered Nov 16 '22 03:11

Darin Dimitrov