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?
This question is related to
regex
In perl:
if($testString =~ /\d/)
{
print "This string contains at least one digit"
}
where \d
matches to a digit.
This:
\d+
should work
Edit, no clue why I added the "+", without it works just as fine.
\d
In Java:
public boolean containsNumber(String string)
{
return string.matches(".*\\d+.*");
}
Another possible solution, in case you're looking for all the words in a given string, which contain a number
\w*\d{1,}\w*
\w*
- Matches 0 or more instances of [A-Za-z0-9_]\d{1,}
- Matches 1 or more instances of a number\w*
- Matches 0 or more instances of [A-Za-z0-9_]The whole point in \w*
is to allow not having a character in the beginning or at the end of a word. This enables capturing the first and last words in the text.
If the goal here is to only get the numbers without the words, you can omit both \w*
.
Hello world 1 4m very happy to be here, my name is W1lly W0nk4
1 4m W1lly W0nk4
Check this example in regexr - https://regexr.com/5ff7q
you could use look-ahead assertion for this:
^(?=.*\d).+$
Ref this
SELECT * FROM product WHERE name REGEXP '[0-9]'
If anybody falls here from google, this is how to check if string contains at least one digit in C#:
With Regex
if (Regex.IsMatch(myString, @"\d"))
{
// do something
}
Info: necessary to add using System.Text.RegularExpressions
With linq:
if (myString.Any(c => Char.IsDigit(c)))
{
// do something
}
Info: necessary to add using System.Linq
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.*
.
Source: Stackoverflow.com