Skip to content
Advertisement

Check and extract a number from a String in Java

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

JavaScript
  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?

Advertisement

Answer

The solution I went with looks like this:

JavaScript

I’m sure it’s not a perfect solution, but it suited my needs. Thank you all for the help. 🙂

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement