Home  >  Article  >  Java  >  How can we extract numbers from input string in Java?

How can we extract numbers from input string in Java?

王林
王林forward
2023-08-17 11:15:472725browse

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.

Example

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);
    }
}

Output

Please enter a string containing numbers on the keyboard: Welcome to Tutorials Point 1234567890 The number is: 1234567890

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete