Check whether a string starts with a digit
Use a start-anchored regular expression and choose ASCII or Unicode digit semantics explicitly for JavaScript, Python, and Java.
Use ^[0-9] to check for an ASCII digit at the start of a string. ^\d is convenient too, but the characters matched by \d depend on the language and regex options. Keep multiline mode off when ^ must refer only to the start of the whole input.
JavaScript
const value = '123abc';
console.log(/^[0-9]/.test(value)); // true
JavaScript's \d also means ASCII digits, including in Unicode mode. Do not add g to a reusable boolean-check regex unless you intend to manage its stateful lastIndex behavior.
Python
import re
value = '123abc'
if re.match(r'[0-9]', value):
print('Starts with an ASCII digit')
else:
print('Does not start with an ASCII digit')
re.match starts at the beginning, so the ^ is unnecessary here. For Python Unicode strings, \d also matches Unicode decimal digits; re.ASCII restricts that shorthand. re.search(r'\d', value) without an anchor can instead find a digit in the middle.
Java
import java.util.regex.Pattern;
String value = "123abc";
boolean startsWithDigit = Pattern.compile("[0-9]")
.matcher(value)
.lookingAt();
lookingAt() checks a prefix. String.matches() requires the whole string to match, so a pattern such as "^\\d.*" must consume the rest and can fail when it contains a line terminator unless the dot behavior is changed. Use a prefix matcher when that is the actual requirement.
Common variations
| Requirement | Prefix pattern, with multiline mode off |
|---|---|
| Starts with an ASCII digit | ^[0-9] |
| Capture leading digits | ^([0-9]+) |
| Starts with a nondigit character | ^[^0-9] |
| Allow leading whitespace | ^\s*[0-9] |
| Allow a minus sign | ^-?[0-9] |
| Read a simple decimal prefix | ^[0-9]+(?:\.[0-9]+)? |
The nondigit pattern requires a character; an empty string does not match. Whitespace semantics also vary, and \s* may accept line breaks. Use [ \t]* if only spaces and tabs are allowed.
To require that the entire input consists of digits, prefer Python's re.fullmatch(r'[0-9]+', value) or Java's value.matches("[0-9]+"). In JavaScript, /^[0-9]+$/.test(value) checks the whole string when multiline mode is off. Do not assume this end-anchor behavior transfers unchanged to every engine: Python's $, for example, can also match before a final newline, which is why re.fullmatch is preferable there.
You can avoid regex for ASCII checks with value.length > 0 && value[0] >= '0' && value[0] <= '9' in JavaScript. Python's bool(value) and value[0].isdigit() has broader Unicode semantics, including some digits that \d does not match.
References: Python regular expressions, Java Pattern, and JavaScript character classes.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan