I'm writing a program where the user enters a String in the following format:
"What is the square of 10?"
.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?
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.
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.
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.
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.
try this
str.matches(".*\\d.*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With