I would like to replace all special characters in a string with a comma (,).
For Example:
Hello@Hello&Hello(Hello)the output -
Hello,Hello,Hello,Hello,(I don't known how to use regexp in C#)
Can i do this work using regexp in C#?
44 Answers
Yes, you can use regular expressions in C#.
Using regular expressions with C#:
using System.Text.RegularExpressions;
string your_String = "Hello@Hello&Hello(Hello)";
string my_String = Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ","); 3 Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):
string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s to pattern: \[^\w\d\s]
You can use a regular expresion to for example replace all non-alphanumeric characters with commas:
s = Regex.Replace(s, "[^0-9A-Za-z]+", ",");Note: The + after the set will make it replace each group of non-alphanumeric characters with a comma. If you want to replace each character with a comma, just remove the +.
Also, It can be done with LINQ
var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();
var output = new string(characters);
Console.WriteLine(output);