How to Extract Numbers from String in Java

You can utilize regular expressions to extract numbers from a string. Here is an example code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "abc123def456";
        Pattern pattern = Pattern.compile("\\d+"); // 匹配一个或多个数字
        Matcher matcher = pattern.matcher(str);

        while (matcher.find()) {
            System.out.println(matcher.group()); // 输出匹配到的数字
        }
    }
}

When running this code, the output will be:

123
456

Regular expressions are used here with \d+ to match one or more numbers, then the find() method of the Matcher object is used to find each matching number one by one, and the group() method is used to retrieve the matched content.

bannerAds