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

Java 正則表達式匹配輸入內容:Pattern 與 Matcher 完整示例

     編輯:關於C++

功能描述

讀取用戶輸入的正則表達式模式,然後循環讀取待匹配字符串,輸出是否匹配及捕獲組詳細信息(組開始/結束位置、括號可視化)。

完整代碼

package regex;

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

public class RegexTest {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter pattern:");
        String patternString = in.nextLine();
        Pattern pattern = Pattern.compile(patternString);

        while (true) {
            System.out.println("Enter String to match: ");
            String input = in.nextLine();
            if (input == null || input.isEmpty()) return;

            Matcher matcher = pattern.matcher(input);
            if (matcher.matches()) {
                System.out.println("Match");
                int g = matcher.groupCount();
                if (g > 0) {
                    // 可視化捕獲組位置
                    for (int i = 0; i < input.length(); i++) {
                        // 處理空組 ()
                        for (int j = 1; j <= g; j++) {
                            if (i == matcher.start(j) && i == matcher.end(j)) {
                                System.out.print("()");
                            }
                        }
                        // 處理組開始 (
                        for (int j = 1; j <= g; j++) {
                            if (i == matcher.start(j) && i != matcher.end(j)) {
                                System.out.print('(');
                            }
                        }
                        System.out.print(input.charAt(i));
                        // 處理組結束 )
                        for (int j = 1; j <= g; j++) {
                            if (i + 1 == matcher.end(j) && i + 1 != matcher.start(j)) {
                                System.out.print(')');
                            }
                        }
                    }
                    System.out.println();
                }
            } else {
                System.out.println("No match");
            }
        }
    }
}

關鍵 API 說明

  • `Pattern.compile(String)`:編譯正則表達式為 Pattern 對象,可復用。
  • `matcher(String)`:創建 Matcher 對象,綁定輸入字符串。
  • `matches()`:嘗試將整個輸入序列匹配模式(等同於 `^pattern$`)。
  • `groupCount()`:捕獲組數量 (不含 group 0 整體匹配)。
  • `start(int group)` / `end(int group)`:指定組在輸入串中的起始/結束索引 (end 為排他)。

示例運行

Enter pattern: (a*)(b*)
Enter String to match: aaabbb
Match
(((aaa)))bbb
Enter String to match: aab
Match
((aa))b
Enter String to match: 
(程序退出)

注意事項

  • `matches()` 要求完全匹配,部分匹配請用 `find()`。
  • 捕獲組索引從 1 開始,0 代表整個匹配。
  • 空組 (如 `a*`) 在匹配空串時 `start == end`,代碼中特殊處理顯示 `()`。
  • 輸入空行或 EOF 退出循環。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved