-4

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 :)

Berk N
  • 5
  • 1
  • 3
  • 5
    Have you tried looking at the javadocs for the method you are using? HINT! – Stephen C Jan 26 '15 at 07:03
  • Ah I tried searching for it but the pattern javadocs did not come up for some reason. I wanted to ask here to make sure I could get the most intuitive answer. Thank you for the hint. – Berk N Jan 26 '15 at 07:14
  • possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – nhahtdh Jan 26 '15 at 07:22

4 Answers4

4
  • . 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

jrarama
  • 829
  • 6
  • 8
1

.* 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.

Jens
  • 60,806
  • 15
  • 81
  • 95
  • 1
    Please be precise. `.*` matches any *sequence* of *characters*, zero or more. (Not a *sign* - '+' or '-'.) And: contain *at least* one digit. – laune Jan 26 '15 at 07:06
0

This is a regular expression.

  • . means any character
  • * means any number (including 0!) of [the matcher before it]
  • \\d is a digit

So, 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.

Mureinik
  • 252,575
  • 45
  • 248
  • 283
0

\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.