I am learning C# and
I have a small testing program where the console should receive a digit as input as and not an alphabetic character.
string inputString;
string pattern = "[A-Za-z]*";
Regex re = new Regex(pattern);
inputString = Console.ReadLine();
while(re.Match(inputString).Success)
{
Console.WriteLine("Please stick to numerals");
inputString = Console.ReadLine();
}
Console.WriteLine(inputString);
Problem is the compiler doesn’t differentiate between an alphabetical character or a numeral.
Any suggestion perhaps
The code seems to be right.
The problem is that
string pattern = "[A-Za-z]*";will also match 0 characters because of the*quantifier.If you only want to check if there is a letter in the string, just use
but of course this is only matching the ASCII letters. The better approach is to use Unicode properties
\p{L}will match any Unicode code point with the property “Letter”.NOTE:
I hope you are aware that this is not checking for only digits, its checking if there is a letter in the input. This will of course accept characters that are not digits and not letters!
If you want to check for only digits you should go for @musefan’s answer or use regex this way
\p{Nd}or\p{Decimal_Digit_Number}: a digit zero through nine in any script except ideographic scripts.See http://www.regular-expressions.info/unicode for more information about Unicode properties.
The next alternative is to check if there is “not a digit” in the input:
The you need to change only the pattern,
\P{Nd}is the negation of\p{Nd}and will match if there is one non digit in the input.