Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to String.Replace

So I was writing some code today that basically looks like this:

string returnString = s.Replace("!", " ")
            .Replace("@", " ")
            .Replace("#", " ")
            .Replace("$", " ")
            .Replace("%", " ")
            .Replace("^", " ")
            .Replace("*", " ")
            .Replace("_", " ")
            .Replace("+", " ")
            .Replace("=", " ")
            .Replace("\", " ")

Which isn't really nice. I was wondering if there's a regex or something that I could write that would replace all the calls to the Replace() function?

like image 266
lomaxx Avatar asked Sep 22 '08 23:09

lomaxx


2 Answers

You can use Regex.Replace(). All of the characters can be placed between square brackets, which matches any character between the square brackets. Some special characters have to be escaped with backslashes, and I use a @verbatim string here, so I don't have to double-escape them for the C# compiler. The first parameter is the input string and the last parameter is the replacement string.

var returnString = Regex.Replace(s,@"[!@#\$%\^*_\+=\\]"," ");
like image 196
Mark Cidade Avatar answered Sep 20 '22 00:09

Mark Cidade


FYI - if you need to modify this regex, you'll need to have an understanding of the regular expression language. It is quite simple, and as a developer you really owe it to yourself to add regular expressions to your toolbox - you don't need them every day, but being able to apply them appropriately where necessary when the need does arise will pay you back tenfold for the initial effort. Here is a link to a website with some top notch, easy to follow tutorials and reference material on regular expressions: regular-expressions.info. Once you get a feel for regular expressions and want to use them in your software, you'll want to buy Regex Buddy. It is a cheap and extraordinary tool for learning and using regular expressions. I very rarely purchase development tools, but this one was worth every penny. It is here: Regex Buddy

like image 24
Nathan Avatar answered Sep 19 '22 00:09

Nathan