3

I want to remove emoji from string, but it doesn't work

string str = "Hello world ☀⛿"; 
string result = Regex.Replace(str, @"\p{Cs}", "");
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
asa
  • 83
  • 1
  • 7

1 Answers1

6

I compared several options I found/thought of:

string text = "Hello world ☀⛿END";

Console.WriteLine(text);
Console.WriteLine(Regex.Replace(text, @"\p{Cs}", ""));
Console.WriteLine(Regex.Replace(text, @"[^\u0000-\u007F]+", ""));
Console.WriteLine(text.Where(c => !Char.IsSurrogate(c)).ToArray());

And this is the outcome:

Hello world ??????END
Hello world ??END
Hello world END
Hello world ??END

I am not sure if your input string, after being copied, pasted here, copied again and pasted into Visual Studio suffers some modification in the process, but from what I see, obviously the second option seems to work better.

Do you want to remove all special characters or only emoji?

Andrew
  • 7,602
  • 2
  • 34
  • 42