I have a regular expression to validate a string. But now I want to remove all the characters that do not match my regular expression.
E.g.
regExpression = @"^([\w\'\-\+])"
text = "This is a sample text with some invalid characters -+%&()=?";
//Remove characters that do not match regExp.
result = "This is a sample text with some invalid characters -+";
Any ideas of how I can use the RegExpression to determine the valid characters and remove all the other ones.
Many thanks
I believe you can do this (whitelist characters and replace everything else) in one line:
var result = Regex.Replace(text, @"[^\w\s\-\+]", "");
Technically it will produce this: "This is a sample text with some invalid characters - +" which is slightly different than your example (the extra space between the - and +).
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