check content of string input

前端 未结 5 698
庸人自扰
庸人自扰 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.

提交回复
热议问题