check content of string input

前端 未结 5 697
庸人自扰
庸人自扰 2020-12-21 01:08

How can I check if my input is a particular kind of string. So no numeric, no \"/\",...

相关标签:
5条回答
  • 2020-12-21 01:16

    It's not entirely clear what you want, but you can probably do it with a regular expression. For example to check that your string contains only letters in a-z or A-Z you can do this:

    string s = "dasglakgsklg";
    if (Regex.IsMatch(s, "^[a-z]+$", RegexOptions.IgnoreCase))
    {
        Console.WriteLine("Only letters in a-z.");
    }
    else
    {
        // Not only letters in a-z.
    }
    

    If you also want to allow spaces, underscores, or other characters simply add them between the square brackets in the regular expression. Note that some characters have a special meaning inside regular expression character classes and need to be escaped with a backslash.

    You can also use \p{L} instead of [a-z] to match any Unicode character that is considered to be a letter, including letters in foreign alphabets.

    0 讨论(0)
  • 2020-12-21 01:20

    Something like this (have not tested) may fit your (vague) requirement.

    if (input is string)
    {
        // test for legal characters?
        string pattern = "^[A-Za-z]+$";
        if (Regex.IsMatch(input, pattern))
        {
             // legal string? do something 
        }
    
        // or
        if (input.Any(c => !char.IsLetter(c)))
        {
             // NOT legal string 
        }
    }
    
    0 讨论(0)
  • 2020-12-21 01:27

    Well, to check that an input is actually an object of type System.String, you can simply do:

    bool IsString(object value)
    {
        return value is string;
    }
    

    To check that a string contains only letters, you could do something like this:

    bool IsAllAlphabetic(string value)
    {
        foreach (char c in value)
        {
            if (!char.IsLetter(c))
                return false;
        }
    
        return true;
    }
    

    If you wanted to combine these, you could do so:

    bool IsAlphabeticString(object value)
    {
        string str = value as string;
        return str != null && IsAllAlphabetic(str);
    }
    
    0 讨论(0)
  • 2020-12-21 01:33
    using System.Linq;
    ...
    
    bool onlyAlphas = s.All(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
    
    0 讨论(0)
  • 2020-12-21 01:36

    If you mean "is the string completely letters", you could do:

    string myString = "RandomStringOfLetters";
    bool allLetters = myString.All( c => Char.IsLetter(c) );
    

    This is based on LINQ and the Char.IsLetter method.

    0 讨论(0)
提交回复
热议问题