Check if a String contains numbers Java

Duane picture Duane · Sep 3, 2013 · Viewed 350.8k times · Source

I'm writing a program where the user enters a String in the following format:

"What is the square of 10?"
  1. I need to check that there is a number in the String
  2. and then extract just the number.
  3. If i use .contains("\\d+") or .contains("[0-9]+"), the program can't find a number in the String, no matter what the input is, but .matches("\\d+")will only work when there is only numbers.

What can I use as a solution for finding and extracting?

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Sep 3, 2013

try this

str.matches(".*\\d.*");