I have got a text string like this:
test1test
I want to check if it contains at least one digit using a regex.
What would this regex look like?
Use the RegExp. test() method to check if a string contains at least one number, e.g. /\d/. test(str) . The test method will return true if the string contains at least one number, otherwise false will be returned.
To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.
Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.
The String. indexOf() method returns the index of the first occurrence of the substring. If the string does not contain the given substring, it returns -1 .
I'm surprised nobody has mentioned the simplest version:
\d
This will match any digit. If your regular expression engine is Unicode-aware, this means it will match anything that's defined as a digit in any language, not just the Arabic numerals 0-9.
There's no need to put it in [
square brackets]
to define it as a character class, as one of the other answers did; \d
works fine by itself.
Since it's not anchored with ^
or $
, it will match any subset of the string, so if the string contains at least one digit, this will match.
And there's no need for the added complexity of +
, since the goal is just to determine whether there's at least one digit. If there's at least one digit, this will match; and it will do so with a minimum of overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With