How to get the count of only special character in a string using Regex?

前端 未结 6 607
轮回少年
轮回少年 2021-01-29 07:44

If my input string is ~!@#$%^&*()_+{}:\"<>?

How do I get the count of each special character using Regex? For example:

Regex.Match         


        
6条回答
  •  感动是毒
    2021-01-29 08:16

    Instead of thinking of every special characters and adding them up, do it the other way; count every letters/digits and subtract them from the count.

    You can do that with a simple one-liner :

    string input = "abc?&;3";
    int numberOfSpecialCharacters = input.Length - input.Count(char.IsLetterOrDigit); //Gives 3
    

    Which you can also change to

    int numberOfSpecialCharacters = input.Count(c => !char.IsLetterOrDigit(c));
    

提交回复
热议问题