Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex remove special characters

Tags:

c#

regex

We need a C# function which will remove all special characters from a string.

Also, is it possible to change "George's" to "George" (remove both single quote and character s)?

like image 810
user374760 Avatar asked Dec 11 '10 18:12

user374760


People also ask

Can regex replace characters?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.


2 Answers

This method will removed everything but letters, numbers and spaces. It will also remove any ' or " followed by the character s.

public static string RemoveSpecialCharacters(string input)
{
    Regex r = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
    return r.Replace(input, String.Empty);
}
like image 109
Ryan Pedersen Avatar answered Oct 23 '22 16:10

Ryan Pedersen


public static string RemoveSpecialCharacters(string input)
{    
    Regex r = new Regex(
                  "(?:[^a-zA-Z0-9 ]|(?<=['\"])s)",
                  RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
    return r.Replace(input, String.Empty);    
}

Ryan's answer is right. Just add A-Z as well as many people would need it.

like image 34
Hash Avatar answered Oct 23 '22 14:10

Hash