java怎么提取字符串中的數(shù)字

小億
217
2023-10-21 21:38:10

要提取字符串中的數(shù)字,可以使用正則表達(dá)式或循環(huán)遍歷字符串的方法。

方法一:使用正則表達(dá)式

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

public class Main {
    public static void main(String[] args) {
        String str = "abc123def456ghi789";
        Pattern pattern = Pattern.compile("\\d+"); // 匹配一個(gè)或多個(gè)數(shù)字
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group()); // 打印匹配到的數(shù)字
        }
    }
}

方法二:使用循環(huán)遍歷字符串

public class Main {
    public static void main(String[] args) {
        String str = "abc123def456ghi789";
        StringBuilder number = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isDigit(c)) {
                number.append(c); // 如果是數(shù)字,追加到StringBuilder中
            } else if (number.length() > 0) {
                System.out.println(number.toString()); // 打印數(shù)字
                number.setLength(0); // 清空StringBuilder
            }
        }
        if (number.length() > 0) {
            System.out.println(number.toString()); // 打印最后一個(gè)數(shù)字
        }
    }
}

以上兩種方法都可以提取字符串中的數(shù)字,使用哪種方法取決于具體的需求和個(gè)人喜好。

0