tags:

views:

108

answers:

6

How to replace different/multiple chars with white space for each instance of character?

characters to be replaced are \ / : * ? < > |

+1  A: 

System.Text.RegularExpressions.Regex.Replace(input, @"[\\/:*?<>|]", " ")

Joren
actually I think you mean. @"[\\/:*\?\<\>\|]", because many of those characters are Reg Ex control characters.
Nick Berardi
Regex control characters are not regex control characters inside a character class, with the exception of `-`, `[` and `\\`.
Abel
and `]` of course...
Abel
You're right, I should've thought about character escapes a bit more. I've edited to something I do think is correct.
Joren
+3  A: 
Regex.Replace(@"my \ special / : string", @"[\\/:*?<>|]", " ");

I might have some of the escapes wrong... :/

JustLoren
No I think you have them correct.
Nick Berardi
Unfortunately, they are wrong and it won't compile. I think you mean this: `Regex.Replace(@"my \ ?? special / : string", @"[\\/:\*?<>|]", " ");` (note that `\?` etc is allowed, but not necessary in a character class)
Abel
@Abel thanks for the clarification.
JustLoren
A: 

Look at the String API methods in C#.

String.replace would work, if you called it seven times.
Or String.indexOfAny in a loop, using String.remove and String.insert.

Going the efficient lines of code way, Regexp.

Dean J
+8  A: 

You can achieve this with string.Split and string.Join:

string myString = string.Join(" ", input.Split(@"\/:*?<>|".ToCharArray()));

Out of curiousity tested this for performance, and it is considerably faster than the Regex approach.

Fredrik Mörk
+1 for originality and an approach I started out with but didn't conclude (and for showing me `string.Join` instead of `Split(..).Join()`) :)
Abel
the funny thing about this answer is that depending on which you are more familiar with, this could be more/less readable than RegEx. But for me, RegEx is more readable.
Aaron Hoffman
agreed, +1 for originality
JustLoren
A: 

Here's a compilable piece of code:

// input
string input = @"my \ ?? spe<<||>>cial / : string";

// regex
string test = Regex.Replace(input, @"[\\/:*?<>|]", " ");

// test now contains "my      spe      cial     string"

Note: this post is a fix of the original JustLoren's code, it's not entirely mine.

Abel
A: 

You can do it using Regex

static void Main(string[] args)       
{        
    string myStr = @"\ / : * ? < > |";
    Regex myRegex = new Regex(@"\\|\/|\:|\*|\?|\<|\>|\|");
    string replaced = myRegex.Replace(myStr, new MatchEvaluator(OnMatch));
    Console.WriteLine(replaced);    
}

private static string OnMatch(Match match)
{
    return " ";
}
Max
when posting code, indent it with four spaces (or click the Code button) to get it correctly colored and laid out.
Abel