Number Validation with Regex in Java
How to validate integers, decimals and formatted numbers in Java with regular expressions, where regex falls short, and how pasted input can break your checks.
Validating numeric input with a regular expression is one of the most common text checks in Java code. It is quick to write and easy to read, but a pattern only answers one question: does this string have the shape of a number? Whether that is enough depends on what the value will be used for. This review covers what a regex check actually does, the patterns that suit common cases, and the places where plain parsing or normalization is the better tool.
Is regex validation suitable for your use?
Regex validation suits format gatekeeping: rejecting obviously malformed input in forms, configuration files, command-line arguments or import pipelines before any further processing. Its main benefit is precision about shape. You decide exactly which signs, separators, decimal points and exponents are allowed, which built-in parsers do not let you control.
The decisive tradeoff is that a pattern knows nothing about numeric value. It cannot tell you that a string of twenty digits will overflow an int or a long, that a value is outside a business range, or that a decimal will lose precision as a double. A string can pass the regex and still fail when parsed.
Parsing alone is often preferable when you only need a valid number and will convert it immediately anyway. Calling Integer.parseInt, Long.parseLong or new BigDecimal inside a try/catch both validates and converts in one step, with range checking included. The most robust approach for user-facing input usually combines the two: a regex to enforce the accepted format, then parsing to confirm the value fits the target type.
What a regex check actually changes
A regex match changes nothing. It reads the string and returns true or false; the stored characters are untouched. This matters because two other steps that often travel alongside validation do change text: trimming whitespace and Unicode normalization. If your workflow trims or normalizes before matching, decide whether you store the original input or the cleaned version, and be consistent about it.
Two Java details govern how a pattern is applied. String.matches and Matcher.matches require the entire string to match, so the anchors ^ and $ are redundant with them. Matcher.find, by contrast, succeeds if any substring matches, so a pattern for digits would accept "abc123xyz" unless you add anchors. Mixing up the two is a frequent source of validation that quietly accepts too much.
The second detail is what \d means. In Java, \d matches only the ASCII digits 0 through 9 by default. With the Pattern.UNICODE_CHARACTER_CLASS flag (or the embedded (?U) flag), it also matches digits from other scripts. Integer.parseInt and Long.parseLong, however, accept any character that Character.digit recognizes as a decimal digit, including many non-ASCII digits. So a parser may accept input that a default \d pattern rejects, and the reverse can happen if you enable the Unicode flag but then hand the string to code that expects ASCII.
Patterns for common number formats
The examples below are written as Java string literals, so each regex backslash is doubled. Text blocks introduced in Java 15 still process escape sequences, so the doubling is needed there too. All examples assume matches(), which requires a full-string match.
Unsigned whole number (one or more digits):
"\\d+"
Signed integer with an optional plus or minus:
"[+-]?\\d+"
Integer without leading zeros (zero itself is allowed):
"[+-]?(0|[1-9]\\d*)"
Decimal number, accepting forms such as 12, 12.5, 12. and .5:
"[+-]?(\\d+(\\.\\d*)?|\\.\\d+)"
Decimal with an optional exponent, such as 1.5e10 or 3E-4:
"[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?"
US-style thousands grouping with an optional decimal part, such as 1,234,567.89. Note that this pattern requires commas once a number has more than three integer digits, so it rejects 1234. If both forms should be accepted, combine it with the plain decimal pattern using alternation.
"[+-]?\\d{1,3}(,\\d{3})*(\\.\\d+)?"
A typical reusable validator compiles the pattern once. Pattern objects are immutable and safe to share across threads; Matcher objects are not, so create a new one per check.
import java.util.regex.Pattern;
public final class NumberValidator {
private static final Pattern SIGNED_INT = Pattern.compile("[+-]?\\d+");
public static boolean isSignedInt(String input) {
return input != null && SIGNED_INT.matcher(input).matches();
}
public static boolean fitsInInt(String input) {
if (!isSignedInt(input)) {
return false;
}
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
The second method shows the combined approach: the regex restricts the format to ASCII digits with an optional sign, and parsing confirms the value is within int range.
How regex compares with built-in parsing
| Approach | Checks format you define | Checks numeric range | Notable behavior |
| Regex with matches() | Yes | No | \d is ASCII-only by default; full-string match required |
| Integer.parseInt / Long.parseLong | Fixed rules only | Yes, throws on overflow | Accepts a leading + or -; accepts non-ASCII decimal digits |
| Double.parseDouble | Fixed rules only | Partly; large values become Infinity | Trims surrounding whitespace; accepts NaN, Infinity, hex floats and a trailing d or f suffix |
| new BigDecimal(String) | Fixed rules only | Arbitrary precision | Accepts exponent notation; throws NumberFormatException on invalid input |
| DecimalFormat / NumberFormat parse | Locale-based | Depends on result type | Lenient: may parse a valid prefix and ignore trailing text unless you check the ParsePosition |
The Double.parseDouble row is the strongest argument for a regex in front of floating-point parsing. Without one, inputs such as "NaN", "Infinity", " 3.5 " or "2f" are accepted, which is rarely what a form field intends.
Will the check hold up with copied and pasted input?
Numbers pasted from word processors, spreadsheets, PDFs or web pages often carry characters that look like ordinary digits and spaces but are not. Common examples include non-breaking spaces used as thousands separators, full-width digits from East Asian input methods, the Unicode minus sign in place of the ASCII hyphen-minus, and invisible characters such as zero-width spaces. A strict ASCII pattern rejects all of these, which is safe but can frustrate users who see a number that looks correct.
If you want to accept such input, clean it explicitly before matching rather than loosening the pattern. Normalizing with java.text.Normalizer in NFKC form converts full-width digits to their ASCII equivalents. Other substitutions, such as replacing a Unicode minus sign or stripping zero-width characters, should be listed deliberately so you know exactly what is being rewritten. Validate the cleaned string, and decide whether the cleaned or original form is what gets stored.
Locale is the other common mismatch. US formatting uses a comma for grouping and a period for decimals, while many other locales reverse these or use spaces. A pattern built for one convention will misread the other: under a US pattern, "1.234" is a small decimal, not one thousand two hundred thirty-four. If your users span locales, either require a single canonical format and say so in the interface, or use locale-aware parsing and confirm the whole string was consumed.
For form fields, readability of the failure matters as much as the check. A rejection with no explanation leaves users guessing which character was wrong. Stating the expected format next to the field, and naming the problem in the error message, helps everyone, including people using screen readers, who cannot easily spot a visually identical but different character. This review does not include testing with specific assistive technologies or browsers, so behavior in a particular environment should be confirmed there.
Pitfalls worth checking
- Using find() without anchors, which accepts any string containing a digit.
- Forgetting that regex does not detect overflow; parse or compare lengths and values separately.
- Assuming \d covers all digits, or assuming it does not, without checking whether UNICODE_CHARACTER_CLASS is set.
- Writing nested quantifiers such as (\d+)+, which can cause severe backtracking on long non-matching input; keep numeric patterns flat.
- Compiling the same Pattern on every call in hot code paths instead of storing it in a static final field.
- Relying on Double.parseDouble alone and unintentionally accepting NaN, Infinity or type suffixes.
- Treating a null input as a non-match by accident; String.matches on null throws a NullPointerException.
Bottom line and evidence gaps
Regex is a good fit when you need to define and enforce an exact numeric format, especially in front of lenient parsers like Double.parseDouble or DecimalFormat. It is not a substitute for range checking, and for simple cases where the value is converted immediately, parsing with exception handling is shorter and catches overflow. Pasted input and locale differences are the main threats to usability; handle them with explicit normalization and clear format guidance rather than looser patterns.
The behavior described here reflects documented Java API semantics. No performance measurements, benchmark results or environment-specific tests were available for this review, so claims about speed, backtracking cost on particular inputs, or rendering in specific applications should be verified against your own JDK version and target environment.