How to find whether a string contains any of the special characters?

后端 未结 10 1262
春和景丽
春和景丽 2020-12-10 01:43

I want to find whether a string contains any of the special characters like !,@,#,$,%,^,&,*,(,)....etc.

How can I do that without looping thorugh all the charact

相关标签:
10条回答
  • 2020-12-10 02:00

    Using PHP, you can try:

    if (preg_match("[^A-Za-z0-9]", $yourString) {
      //DO WHATEVER
    }
    

    This will return TRUE if the string contains anything other than a letter or number.

    Hope this helps.

    0 讨论(0)
  • 2020-12-10 02:01
      Regex RgxUrl = new Regex("[^a-z0-9]");
                        blnContainsSpecialCharacters = RgxUrl.IsMatch(stringToCheck);
    
    0 讨论(0)
  • 2020-12-10 02:06
    //apart from regex we can also use this
    string input = Console.ReadLine();
                char[] a = input.ToCharArray();
                char[] b = new char[a.Length];
                int count = 0;
                for (int i = 0; i < a.Length; i++)
                {
                    if (!Char.IsLetterOrDigit(a[i]))
                    {
                        b[count] = a[i];
                        count++;
                    }
                }
                Array.Resize(ref b, count);
                foreach(var items in b)
                {
                    Console.WriteLine(items);
                }
                Console.ReadLine();
    //it will display the special characters in the string input
    
    0 讨论(0)
  • 2020-12-10 02:07
    public static bool HasSpecialCharacters(string str)
    {
      string specialCharacters = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" +"\"";
      char[] specialCharactersArray = specialCharacters.ToCharArray();
    
      int index = str.IndexOfAny(specialCharactersArray);
      //index == -1 no special characters
      if (index == -1)
        return false;
      else
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题