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

How can we extract numbers from input string in Java?

王林
Release: 2023-08-17 11:15:47
forward
2811 people have browsed it

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);
    }
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template