Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a String contains numbers Java

Tags:

java

string

regex

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?

like image 967
Duane Avatar asked Oct 14 '22 14:10

Duane


People also ask

How do you check if a string contains only numbers?

Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.

How do you check if a string is all digits in Java?

To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if the characters in the given string are digits.

How do you find a number in a string?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

Can string contain numbers?

A string consists of one or more characters, which can include letters, numbers, and other types of characters. You can think of a string as plain text. A string represents alphanumeric data.


1 Answers

try this

str.matches(".*\\d.*");
like image 81
Evgeniy Dorofeev Avatar answered Oct 21 '22 09:10

Evgeniy Dorofeev