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

Java 正則表達式實戰:郵箱提取與代碼統計雙案例

     編輯:Java 相關知識

案例一:網頁郵箱地址提取器

正則設計

String emailRegex = "[\\w.-]+@[\\w.-]+\\.\\w+";
  • \\w = [a-zA-Z0-9_],.- 允許點和連字符。
  • + 至少一個字符,@ 分隔,域名部分同理。

完整代碼

public class EmailSpider {
    private static final Pattern EMAIL_PATTERN = Pattern.compile("[\\w.-]+@[\\w.-]+\\.\\w+");

    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("emailSpider.html"))) {
            String line;
            while ((line = br.readLine()) != null) {
                extract(line);
            }
        } catch (IOException e) { e.printStackTrace(); }
    }

    private static void extract(String line) {
        Matcher m = EMAIL_PATTERN.matcher(line);
        while (m.find()) System.out.println(m.group());
    }
}

輸出示例:

867124664@qq.com
260678675@QQ.com
hr_1985@163.com
...

案例二:Java 源碼行數統計器(正常/註釋/空白行)

核心邏輯

  • 單行註釋://...
  • 多行註釋:/* ... */(跨行需狀態機)。
  • 空白行:^\\s*$(去除首尾空白後為空)。

關鍵代碼片段

boolean inBlockComment = false;
while ((line = br.readLine()) != null) {
    line = line.trim();
    if (line.isEmpty()) { whiteLines++; continue; }

    if (inBlockComment) {
        commentLines++;
        if (line.endsWith("*/")) inBlockComment = false;
    } else if (line.startsWith("/*")) {
        commentLines++;
        if (!line.endsWith("*/")) inBlockComment = true;
    } else if (line.startsWith("//")) {
        commentLines++;
    } else {
        normalLines++;
    }
}

運行結果示例

normalLines: 1245
commentLines: 312
whiteLines: 187

正則性能優化提示

  1. 預編譯 Pattern:靜態常量,避免重複編譯。
  2. 避免過度捕獲組:非捕獲組 (?:...) 減少內存。
  3. 錨點優化:^ $ 縮小回溯範圍。
  4. 佔有量詞:++ *+ 禁用回溯(確定模式下)。

總結

兩個實戰案例展示了正則在文本提取與代碼分析中的核心價值。掌握 Pattern/Matcher API、狀態機處理多行註釋、預編譯優化,即可應對 90% 的文本處理需求。

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