I am trying to make a catch exception for input string for example
if user enters
123test456
the program to say
The first 3 characters must be letter
so it should accept
wowTest456
You can use Take()
, with .All()
including letter condition,
var validString = inputString
.Take(3)
.All(x => Char.IsLetter(x));
You can solve it using Regex
too. Credit to @JohnathanBarclay.
bool isInvalidString = Regex.IsMatch(inputString, @"^\d{3}");
Explanation:
^
: Matches the beginning of the string \d
: Matches the digit characters {3}
: Matches 3 tokens. To make it positive regex just check \w
instead of \d
bool validString = Regex.IsMatch(inputString, @"^\w{3}");
Using \w
includes _
(underscore) as well, if you don't want _
as a part of first three letters, then you can use range like below
bool validString = Regex.IsMatch(inputString, @"^[a-zA-Z]{3}");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.