3

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

string str = "Hello world 😀🙏☀⛿"; 
string result = Regex.Replace(str, @"\p{Cs}", "");
7
  • What is that regex supposed to do? It doesn't look even remotely useful for your purpose.
    – Andrew
    Dec 6, 2016 at 18:43
  • 1
    I think the solution is blindly taken from stackoverflow.com/a/28025891/3832970 Dec 6, 2016 at 18:50
  • Oh, if Jon Skeet suggested that, then it must work. I just tried it with an online regex page that doesn't support that.
    – Andrew
    Dec 6, 2016 at 18:55
  • Is the last one in the string an emoji char? It is a flag. Dec 6, 2016 at 19:00
  • 1
    @asa: I cannot test anything because you have not posted the requirements. What is an emoji for you? What Unicode ranges do you need to cover? Dec 6, 2016 at 19:15

1 Answer 1

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?

3
  • 3
    Regex.Replace(str, @"[^\u0000-\u007F]+", ""); works and thanks
    – asa
    Dec 6, 2016 at 19:17
  • 3
    However, it does not only match "emojis", it will remove Cyrillic letters and much more. Dec 6, 2016 at 19:17
  • 2
    Exactly. My guess is that @asa just needs to remove strange characters and doesn't expect anything special. Is that right?
    – Andrew
    Dec 6, 2016 at 19:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.