Home >Java >javaTutorial >How can we extract numbers from input string in Java?
java.lang.String class provides many methods to process strings. Through these methods, operations such as trimming, concatenation, conversion and comparison can be performed on strings. We can extract numbers from a given string using the replaceAll() method of the String class.
import java.util.Scanner; public class StringExtractTest { public static void main(String[] args) { String input; String numbers; Scanner scanner = new Scanner(System.in); System.out.print(" 请输入一个包含数字的字符串:"); input = scanner.nextLine(); numbers = input.replaceAll("[^0-9]", ""); System.out.println("数字是:" + numbers); } }
The above is the detailed content of How can we extract numbers from input string in Java?. For more information, please follow other related articles on the PHP Chinese website!