tags:

views:

64

answers:

6

Hi!

I have got a text string like this:

test1test

and I want to check if it contains at least on digit using a regex.

How would this regex look like?

A: 

Ref this

SELECT * FROM product WHERE name REGEXP '[0-9]'
Salil
Fails for the string "bla1bla"
Jurgen
check again? '^[0-9]' should be '[0-9]'
Salil
A: 

This:

\d+

should work

Edit, no clue why I added the "+", without it works just as fine.

\d
Jurgen
A: 

In perl:

if($testString =~ /\d/) 
{
    print "This string contains at least one digit"
}

where \d matches to a digit.

Kyra
That's over-complex. `\d` is enough.
Donal Fellows
+1  A: 

you could use look-ahead assertion for this:

^(?=.*\d).+$
SilentGhost
Good grief, why make it that complicated?
Joe White
@Joe: because most likely it's not the only check OP needs to do
SilentGhost
+1  A: 

The regular expression you are looking for is simply this:

[0-9]

You do not mention what language you are using. If your regular expression evaluator forces REs to be anchored, you need this:

.*[0-9].*

Some RE engines (modern ones!) also allow you to write the first as \d (mnemonically: digit) and the second would then become .*\d.*.

Donal Fellows
+3  A: 

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.

Joe White