Check Whether a String Contains Numbers with Regex

How to check if a string contains numbers with regex: [0-9] vs \d, Unicode and styled digits, anchors, and copy-paste pitfalls across JavaScript, Python, Java and .NET.

Checking whether a string contains a digit takes one of the shortest regular expressions you can write. Results still differ between languages for three reasons: which characters count as a digit, whether the function searches the string or must match all of it, and what "number" means for your data. This review covers when a regex check fits, what it changes, and how to keep a pattern working when you move it between tools.

Scope of evidence: this article relies on documented behavior of common regex engines and on Unicode character properties. No test results for a specific regex tester, form library or assistive technology were supplied. Check engine behavior against the documentation for the version you run.

Is a regex digit check right for your use?

A regex works well for the question "does this string contain at least one digit from 0 to 9?" You need one short pattern, every mainstream language supports it, and testing the input does not modify it. The main tradeoff is that the shorthand \d means different things in different engines. Some match only ASCII 0–9, and others match any Unicode decimal digit, so the same pattern can accept different input. If you need predictable results, write the class [0-9] explicitly.

Use something other than a digit pattern when you need to know whether the string is a valid number. Signs, decimal points, thousands separators, exponents and locale conventions all complicate the check, and your language's number parser usually handles them more reliably than a hand-written pattern. Digit classes also cannot detect numbers written as words, such as "three", or as Roman numerals.

What "contains numbers" can mean

  • Contains at least one digit character: "order 66" qualifies.
  • Consists only of digits: "12345" qualifies, "123a" does not.
  • Contains a numeric value such as -3.5 or 1,200: this needs a number pattern or a parser, not just a digit class.
  • Contains number words such as "twelve": this is outside what digit classes detect.

The core patterns

A "contains a digit" check needs a search-style function, which looks anywhere in the string. An "only digits" check needs the pattern anchored to the whole string. Most bugs come from mixing up the two kinds of function.

// JavaScript
const hasDigit = /[0-9]/;
hasDigit.test("abc1");    // true
hasDigit.test("abc");     // false

const onlyDigits = /^[0-9]+$/;
onlyDigits.test("12345"); // true
onlyDigits.test("123a");  // false
# Python
import re

re.search(r"[0-9]", "abc1") is not None       # True
re.fullmatch(r"[0-9]+", "12345") is not None  # True
re.match(r"[0-9]", "abc1")                    # None: match() only checks the start
// Java
import java.util.regex.Pattern;

Pattern.compile("[0-9]").matcher("abc1").find(); // true
"abc1".matches("[0-9]");                          // false: matches() needs the whole string

What the check actually changes

Testing a string does not change it. Functions such as test(), search() and find() read the input and return a boolean or a match object. The stored characters stay the same. The text changes only when a workflow goes on to replace or normalize, for example by removing digits with replace(/[0-9]/g, "") or by converting styled digits to plain ones. Keep validation and transformation as separate steps so that a check never alters data without anyone noticing.

\d versus [0-9]: which characters count as digits

Unicode defines many decimal digits beyond ASCII. Examples include fullwidth digits (123), Arabic-Indic digits (٣), Devanagari digits (३), and the Mathematical Alphanumeric Symbols digits, such as bold 𝟏, that "fancy font" generators produce. All of these have the Unicode general category Nd (decimal number). Superscript digits such as ² have category No (other number) instead, so a Unicode-aware \d does not match them.

Engine | Default meaning of \d | How to change it
JavaScript | ASCII 0–9 only, even with the u flag | Use \p{Nd} with the u or v flag for Unicode digits
Python 3 re (str patterns) | Any Unicode decimal digit (Nd) | The re.ASCII flag restricts it to 0–9
Java | ASCII 0–9 | The UNICODE_CHARACTER_CLASS flag, or \p{Nd}
.NET | Any Unicode decimal digit (Nd) | RegexOptions.ECMAScript restricts it to 0–9
Go (RE2) | ASCII 0–9 | Use \p{Nd} for Unicode digits

In practice, re.search(r"\d", "123") finds a match in Python, while /\d/.test("123") returns false in JavaScript. Downstream code differs in the same way. Python's int() accepts Unicode decimal digits, so int("123") returns 123. JavaScript's Number("123") and parseInt("123") return NaN. If the next step expects ASCII digits, as most databases, APIs and parsers do, use [0-9] so that validation and parsing agree.

Normalizing styled digits before the check

If users paste text from styled-text tools, NFKC normalization can convert compatibility digits to ASCII before you test the string. It maps fullwidth 1 to 1, mathematical bold 𝟏 to 1, and superscript ² to 2. Unlike the check itself, normalization changes the stored characters, and sometimes the meaning: "x²" becomes "x2". It also leaves digits from other scripts alone, because Arabic-Indic and Devanagari digits are not compatibility characters. Decide whether you want to normalize, reject, or accept those inputs as they are.

// JavaScript
"𝟏𝟐3".normalize("NFKC");             // "123"

# Python
import unicodedata
unicodedata.normalize("NFKC", "x²")  # 'x2'

Anchors and the whole-string trap

In Python and .NET, $ can match just before a trailing newline, so ^[0-9]+$ accepts "123\n" as all digits. To require the true end of the string, use re.fullmatch or \Z in Python, and \z in .NET. In JavaScript, $ without the m flag matches only at the very end.

Some APIs anchor implicitly. Java's String.matches() must match the entire input, which is why "abc1".matches("[0-9]") is false. The common workaround ".[0-9]." fails on multi-line input because . does not match line breaks by default, so use find() instead. The HTML pattern attribute must also match the entire field value, so pattern="[0-9]+" behaves as "only digits", not "contains a digit".

The JavaScript global-flag pitfall

A JavaScript regex with the g flag remembers its position in lastIndex between calls. If you reuse one such regex with test(), the results alternate on identical input. Leave out the g flag for yes/no checks.

const re = /[0-9]/g;
re.test("a1"); // true
re.test("a1"); // false: lastIndex was left at 2, then resets to 0

Copying patterns between tools and languages

A pattern that works in a regex tester can break when you paste it into code. In Java and in C# regular string literals, the backslash must be escaped, so \d becomes "\d". Python raw strings (r"\d") and JavaScript regex literals (/\d/) keep the backslash as typed, but new RegExp("\d") needs the escape. Online testers also default to a particular engine flavor. Set the tester to the engine your code runs on, or the \d behavior described above may not match what you see.

Text copied from word processors, chat apps or web pages can carry invisible characters such as zero-width spaces or non-breaking spaces. These do not change whether a string contains a digit, but they make an only-digits check fail on input that looks like plain digits. Printing the code points shows what is actually there.

[..."12\u200B3"].map(c => c.codePointAt(0).toString(16));
// [ '31', '32', '200b', '33' ]

Readability, accessibility and search

The check produces no visible output, but users feel its effect when it drives form validation. Error messages should describe what is accepted, such as "digits 0–9 only", rather than show the pattern. Client-side checks, including the HTML pattern attribute, can be bypassed, so repeat the validation on the server.

Styled and fullwidth digits may be read aloud, matched in search, or sorted differently from ASCII digits. No documentation or scoped test for a specific screen reader, search engine or destination platform was supplied for this article, so treat any particular behavior as unverified and test with the environments you support. When the data will be displayed, searched or read by assistive technology, storing a plain ASCII-digit version is the safer choice.

Choosing the right check

  • At least one ASCII digit: [0-9] with test(), search() or find().
  • Only ASCII digits: fullmatch in Python, matches() in Java, ^[0-9]+$ in JavaScript, \A[0-9]+\z in .NET.
  • Any Unicode decimal digit: \p{Nd} in JavaScript (u or v flag), Java and Go, or the default \d in Python and .NET.
  • Styled digits from pasted text: normalize with NFKC first, accepting that the stored text changes.
  • A real numeric value: parse with your language's number parser and handle its errors instead of relying only on a digit pattern.