Question

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?

Was it helpful?

Solution

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,@"[!@#\$%\^*_\+=\\]"," ");

OTHER TIPS

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

s/[!@#$%^*_+=\]/ /

Would be the regex for it... in c# you should be able to use

Regex.Replace(yourstring, "[!@#$%^*_+=\]", "" ); 

Though my C# is rusty..

If you don't care to delve into Regex, here are a couple of other extension-method possibilities.

You can pass in the specific characters you want to replace:

static public string ReplaceCharsWithSpace(this string original, string chars)
{
    var result = new StringBuilder();
    foreach (var ch in original)
    {
        result.Append(chars.Contains(ch) ? ' ' : ch);
    }
    return result.ToString();
}

Or if you know you want to only keep or only strip out specific types of characters, you can use the various methods in char, such as IsLetter, IsDigit, IsPunctuation, and IsSymbol:

static public string ReplaceNonLetterCharsWithSpace(this string original)
{
    var result = new StringBuilder();
    foreach (var ch in original)
    {
        result.Append(char.IsLetter(ch) ? ch : ' ');
    }
    return result.ToString();
}

Here's how you'd use each of these possibilities:

string s = "ab!2c";
s = s.ReplaceCharsWithSpace(@"!@#$%^*_+=/");  // s contains "ab  c"

string t = "ab3*c";
t = t.ReplaceNonLetterCharsWithSpace();  // t contains "ab  c"

Maybe you can reduce this down to a couple of lines, if desired, by using a Lambda expression and List<>, ForEach

using System.Collections.Generic;

namespace ReplaceWithSpace 
 {
    class Program 
    {
        static void Main(string[] args) 
        {
            string someString = "#1, 1+1=2 $string$!";

            var charsToRemove = new List<char>(@"!@#$%^*_+=\");
            charsToRemove.ForEach(c => someString = someString.Replace(c, ' '));

            System.Diagnostics.Debug.Print(someString); //" 1, 1 1 2  string  "
        }
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top