首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 正則表達式提取字符串中數字完整示例

     編輯:Java 相關知識

需求場景

從混雜字符串 "3a7s10@5d2a6s17s56;33" 中提取所有數字,轉為整數集合 [3, 7, 10, 5, 2, 6, 17, 56, 33]。

核心代碼

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

public class NumberExtractor {
    public static List<Integer> extractNumbers(String input) {
        List<Integer> result = new ArrayList<>();
        if (input == null || input.isEmpty()) return result;

        // 1. 非數字替換為空格
        Pattern pattern = Pattern.compile("[^0-9]");
        Matcher matcher = pattern.matcher(input);
        String onlyNumbers = matcher.replaceAll(" ").trim();

        // 2. 按空格分割獲取數字字符串數組
        String[] numStrs = onlyNumbers.split("\\s+");

        // 3. 轉換為 Integer
        for (String s : numStrs) {
            if (!s.isEmpty()) {
                result.add(Integer.parseInt(s));
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String str = "3a7s10@5d2a6s17s56;33";
        List<Integer> numbers = extractNumbers(str);
        System.out.println(numbers); // [3, 7, 10, 5, 2, 6, 17, 56, 33]
    }
}

關鍵點解析

  1. 正則 [^0-9]:匹配「非 0-9 字符」,配合 replaceAll(" ") 將所有非數字統一替換為空格。
  2. split("\\s+"):按「一個或多個空白字符」分割,自動處理連續非數字產生的多空格。
  3. trim():去除首尾空格,避免產生空字符串元素。

常用正則速查表

常用正則表達式速查表

  • \d / [0-9]:數字
  • \D / [^0-9]:非數字
  • \w:字母數字下劃線
  • \s:空白字符
  • +:≥1 次,*:≥0 次,?:0/1 次
  • ():分組捕獲

進階變體:提取連續數字作為整體

若需保留「10」而非拆分為「1」「0」,改用 \\d+ 直接匹配:

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.println(Integer.parseInt(m.group()));
}
// 輸出:3, 7, 10, 5, 2, 6, 17, 56, 33

此法更簡潔,性能略優,推薦實戰使用。

總結

正則表達式是文本處理利器,掌握 Pattern/Matcher 雙引擎與常用元字符,能輕鬆解決提取、替換、驗證等 90% 字符串問題。實戰中優先考慮 \\d+ 直接匹配數字組,代碼更清晰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved