0

I have requirement to remove all the special characters from any string except " and ' .

ClientName = Regex.Replace(ClientName, @"\(.*?\)", " ").Trim();

This is the regex I am using. I want exclude all the special characters except " and '.

Example:

clientName= "S"unny, Cool. Mr"

Output should be

"S"unny Cool Mr"
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
viswadev
  • 21
  • 2
  • 3
    Does this answer your question? [Regex for removing only specific special characters from string](https://stackoverflow.com/questions/42045115/regex-for-removing-only-specific-special-characters-from-string), the answer is the same, just include the one's you *want* to remove. – Trevor Aug 03 '20 at 16:43
  • 1
    If you don't want to use `Regex` you could always use `string.Replace / string.Remove`, just a thought. – Trevor Aug 03 '20 at 16:49
  • There is no such thing as a "special" character so that's a bad search term. You need to explicitly define what you want included in the output. You appear to want letters, whitespace, single quotes and double quotes. – CodeCaster Aug 03 '20 at 16:49

1 Answers1

1

Consider using the following pattern:

@"[^\p{L}\p{Nd}'""\s]+"

This will target all special characters while also excluding single and double quote, as well as whitespace.

string clientName = "S\"unny, Cool. Mr";
string output = Regex.Replace(clientName, @"[^\p{L}\p{Nd}'""]+", "");
Console.WriteLine(output);

This prints:

S"unny Cool Mr

The character classes \p{L} and \p{N} represent all Unicode letters and numbers, so placing them into a negative character class means remove anything which is not a number or letter.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360