Regex for numbers only in C#

Learn regex for numbers only in c# with practical examples, diagrams, and best practices. Covers c#, regex, string development techniques with visual explanations.

Mastering Regex for Numbers Only in C#

Hero image for Regex for numbers only in C#

Learn how to effectively use regular expressions in C# to validate and extract strings containing only numeric digits, covering common scenarios and best practices.

Regular expressions (regex) are powerful tools for pattern matching in strings. In C#, they are frequently used for validation, parsing, and data extraction. A common requirement is to determine if a string consists solely of numeric digits. This article will guide you through various regex patterns and C# methods to achieve this, from basic validation to handling optional signs and decimal points.

Basic Numeric Validation: Digits Only

The simplest case is to check if a string contains only digits (0-9). The regex pattern for a single digit is \d. To match one or more digits, we use the + quantifier. To ensure the entire string consists only of digits, we anchor the pattern to the beginning (^) and end ($) of the string. This prevents partial matches.

using System.Text.RegularExpressions;

public class NumericValidator
{
    public static bool IsDigitsOnly(string input)
    {
        // ^ asserts position at the start of the string.
        // \d matches a digit (0-9).
        // + matches the previous token one or more times.
        // $ asserts position at the end of the string.
        return Regex.IsMatch(input, "^\\d+$");
    }

    public static void Main(string[] args)
    {
        Console.WriteLine($"'12345' is digits only: {IsDigitsOnly("12345")}"); // True
        Console.WriteLine($"'123.45' is digits only: {IsDigitsOnly("123.45")}"); // False
        Console.WriteLine($"'abc' is digits only: {IsDigitsOnly("abc")}");     // False
        Console.WriteLine($"'' is digits only: {IsDigitsOnly("")}");         // False (because of +)
        Console.WriteLine($"' ' is digits only: {IsDigitsOnly(" ")}");         // False
    }
}

C# example for validating strings containing only digits.

Handling Optional Signs and Decimal Points

Real-world numbers often include an optional leading sign (+ or -) and a decimal point. We can extend our regex to accommodate these. The ? quantifier makes the preceding element optional (zero or one occurrence). For the decimal part, we can match a literal dot \. followed by one or more digits \d+. We make the entire decimal part optional by grouping it with parentheses () and applying ?.

using System.Text.RegularExpressions;

public class AdvancedNumericValidator
{
    public static bool IsDecimalNumber(string input)
    {
        // ^ asserts position at the start of the string.
        // [+-]? matches an optional plus or minus sign.
        // \d+ matches one or more digits.
        // (\.\d+)? matches an optional decimal part (a dot followed by one or more digits).
        // $ asserts position at the end of the string.
        return Regex.IsMatch(input, "^[+-]?\\d+(\\.\\d+)?$");
    }

    public static void Main(string[] args)
    {
        Console.WriteLine($"'123' is a decimal number: {IsDecimalNumber("123")}");       // True
        Console.WriteLine($"'-123' is a decimal number: {IsDecimalNumber("-123")}");     // True
        Console.WriteLine($"'+123.45' is a decimal number: {IsDecimalNumber("+123.45")}"); // True
        Console.WriteLine($"'0.5' is a decimal number: {IsDecimalNumber("0.5")}");       // True
        Console.WriteLine($"'.5' is a decimal number: {IsDecimalNumber(".5")}");         // False (requires leading digit)
        Console.WriteLine($"'123.' is a decimal number: {IsDecimalNumber("123.")}");     // False (requires trailing digit after dot)
        Console.WriteLine($"'abc' is a decimal number: {IsDecimalNumber("abc")}");       // False
    }
}

C# example for validating strings representing decimal numbers with optional signs.

Regex for Integer vs. Floating-Point Numbers

Sometimes you need to distinguish between integers and floating-point numbers. The previous pattern ^[+-]?\d+(\.\d+)?$ covers both. Here's how you can create more specific patterns.

flowchart TD
    A[Input String] --> B{Is Integer?}
    B -- Yes --> C[Valid Integer]
    B -- No --> D{Is Floating-Point?}
    D -- Yes --> E[Valid Floating-Point]
    D -- No --> F[Invalid Number]

Decision flow for validating different number types.

using System.Text.RegularExpressions;

public class NumberTypeValidator
{
    // Matches integers (e.g., "123", "-45", "+0")
    public static bool IsInteger(string input)
    {
        return Regex.IsMatch(input, "^[+-]?\\d+$");
    }

    // Matches floating-point numbers (e.g., "1.23", "-0.5", "+10.0")
    // Requires at least one digit before and after the decimal point if present.
    public static bool IsFloatingPoint(string input)
    {
        // This pattern ensures that if a decimal point is present, there are digits on both sides.
        // It also allows for numbers without a decimal point (integers).
        // A more strict floating-point only would exclude integers: ^[+-]?\d+\.\d+$
        return Regex.IsMatch(input, "^[+-]?\\d*\\.\\d+$|^[+-]?\\d+$");
    }

    public static void Main(string[] args)
    {
        Console.WriteLine($"'123' is integer: {IsInteger("123")}");             // True
        Console.WriteLine($"'-45' is integer: {IsInteger("-45")}");             // True
        Console.WriteLine($"'123.0' is integer: {IsInteger("123.0")}");         // False

        Console.WriteLine($"'1.23' is floating-point: {IsFloatingPoint("1.23")}"); // True
        Console.WriteLine($"'-0.5' is floating-point: {IsFloatingPoint("-0.5")}"); // True
        Console.WriteLine($"'123' is floating-point: {IsFloatingPoint("123")}");   // True (as it's a valid number)
        Console.WriteLine($"'.5' is floating-point: {IsFloatingPoint(".5")}");     // True (due to \d* before \.)
    }
}

C# examples for distinguishing between integer and floating-point numbers using regex.