I have the following regex to validate only for integers, ^\$?\d{0,10}(.(\d{0,2}))?$ While it correctly identifies 12 as a valid integer, it also validates $12 as a valid one. If, I remove the first $ from the regex it doesn't work either.
Thanks
I have the following regex to validate only for integers, ^\$?\d{0,10}(.(\d{0,2}))?$ While it correctly identifies 12 as a valid integer, it also validates $12 as a valid one. If, I remove the first $ from the regex it doesn't work either.
Thanks
using System;
using System.Text.RegularExpressions;
Console.WriteLine(Regex.IsMatch("1313123", @"^\d+$")); // true
That assumes we want to validate a simple integer.
If we also want to include thousands grouping structures for one or more cultures or other numeric conventions, that will be more complicated. Consider these cases:
10,000
10 000
100,00
100,000
-10
+10
For a sense of the challenge, see the NumberFormatInfo
properties here.
If we need to handle culture specific numeric conventions, it's probably best to leverage the Int64.TryParse()
method instead of using Regex.
It's live here. The complete list of NumberStyles is here. We can add/remove the various NumberStyles
until we find the set that we want.
using System;
using System.Text.RegularExpressions;
using System.Globalization;
public class Program
{
public static void Main()
{
Console.WriteLine(IsIntegerRegex("")); // false
Console.WriteLine(IsIntegerRegex("2342342")); // true
Console.WriteLine(IsInteger("1231231.12")); // false
Console.WriteLine(IsInteger("1231231")); // true
Console.WriteLine(IsInteger("1,231,231")); // true
}
private static bool IsIntegerRegex(string value)
{
const string regex = @"^\d+$";
return Regex.IsMatch(value, regex);
}
private static bool IsInteger(string value)
{
var culture = CultureInfo.CurrentCulture;
const NumberStyles style =
// NumberStyles.AllowDecimalPoint |
// NumberStyles.AllowTrailingWhite |
// NumberStyles.AllowLeadingWhite |
// NumberStyles.AllowLeadingSign |
NumberStyles.AllowThousands;
return Int64.TryParse(value, style, culture, out _);
}
}