18

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?

4
  • @lomaxx: See dimitre's solution, which avoids using regex at all. Commented Dec 9, 2008 at 14:57
  • @Cawas: Here: dnovatchev.spaces.live.com/blog/cns!44B0A32C2CCF7488!353.entry See a description of the XPath translate() function here: w3.org/TR/xpath-functions/#func-translate Commented May 11, 2010 at 19:23
  • @dimitre cool, xpath is nice. But how could I have found this just from your comment? Commented May 11, 2010 at 21:44
  • @Cawas: I deleted my answer almost immediately after posting it in Dec. 2008 (got two downvotes in no time). Unfortunately, for many people interested in c#, even mentioning XSLT is offensive :(. Such people lose their ability for rational/critical thinking. Commented May 11, 2010 at 22:15

5 Answers 5

32

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,@"[!@#\$%\^*_\+=\\]"," ");
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

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

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

Though my C# is rusty..

Comments

0

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"

Comments

0

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  "
        }
    }

}

1 Comment

The trouble with this approach is a lot of intermediate strings are generated for each character replaced. Which is the same problem the original question had that the regex solution solves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.