example: if(str.matches(".*\\d.*"))
I used it recently to check if a value of an array contained a number.
What's the logic behind it? Why is the .* .*
there? What does \\d
mean?
EDIT: thank you all! such fast responses :)
example: if(str.matches(".*\\d.*"))
I used it recently to check if a value of an array contained a number.
What's the logic behind it? Why is the .* .*
there? What does \\d
mean?
EDIT: thank you all! such fast responses :)
.
symbol matches any character except newline. *
repeats the character behind it 0 or more times. \d
matches any digit. The extra \
in \\d
is used to escape the backslash from the string.So .\\d.
matches any single character, a digit, and any single character. It will match the following: a1b
, p3k
, &2@
.*\\d.*
matches 0 or more characters, a digit, and 0 or more characters. It will match the following: 2
, 11
, 123
, asdf6klj
If you want to match 1 or more characters you can use +
, {2,}
, {3,5}
, etc.
+
means repeat previous character 1 or more times.
{2, }
means repeat previous character two or more times.
{3, 5}
means repeat previous character 3 to 5 times.
For more details you can review many regex tutorials such as here:
http://www.tutorialspoint.com/java/java_regular_expressions.htm
.*
means any squence of character. it matches zero eo more character .
\\d
means a digit
So you match all strings that contains one digit. For more information see the documentation of Pattern class.
This is a regular expression.
.
means any character*
means any number (including 0!) of [the matcher before it]\\d
is a digitSo, id you put it all together, this regex matches a string that has the following: Any number of any character, then a digit, and then any number of any character. If we translate this "formal" description to a more human readable one, it just means a string that has a digit somewhere in it.
\d means if there is any digit but '\' is an escape sequence hence '\\'
is used.
In C#, you can also use @".*\d.*"
(Not sure in Java but I feel it should work)
*
denotes any number of characters.