How do I strip non-alphanumeric characters (including spaces) from a string?

前端 未结 8 2318
借酒劲吻你
借酒劲吻你 2020-12-14 00:10

How do I strip non alphanumeric characters from a string and loose spaces in C# with Replace?

I want to keep a-z, A-Z, 0-9 and nothing more (not even \" \" spaces).<

相关标签:
8条回答
  • 2020-12-14 00:56

    You can use Linq to filter out required characters:

      String source = "Hello there(hello#)";
    
      // "Hellotherehello"
      String result = new String(source
        .Where(ch => Char.IsLetterOrDigit(ch))
        .ToArray());
    

    Or

      String result = String.Concat(source
        .Where(ch => Char.IsLetterOrDigit(ch)));  
    

    And so you have no need in regular expressions.

    0 讨论(0)
  • 2020-12-14 00:57

    The mistake made above was using Replace incorrectly (it doesn't take regex, thanks CodeInChaos).

    The following code should do what was specified:

    Regex reg = new Regex(@"[^\p{L}\p{N}]+");//Thanks to Tim Pietzcker for regex
    string regexed = reg.Replace("Hello there(hello#)", "");
    

    This gives:

    regexed = "Hellotherehello"
    
    0 讨论(0)
提交回复
热议问题