Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Check if string contains at least one digit

Tags:

regex

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?

like image 800
crauscher Avatar asked Jul 05 '10 14:07

crauscher


People also ask

How do you know if a string has at least one digit?

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.

How do I check if a string contains a digit?

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.

What does '$' mean in regex?

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.

How do you check if a string contains a substring regex?

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 .


1 Answers

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.

like image 114
Joe White Avatar answered Oct 08 '22 22:10

Joe White