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
...
//.../* ... */(跨行需狀態機)。^\\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
(?:...) 減少內存。^ $ 縮小回溯範圍。++ *+ 禁用回溯(確定模式下)。兩個實戰案例展示了正則在文本提取與代碼分析中的核心價值。掌握 Pattern/Matcher API、狀態機處理多行註釋、預編譯優化,即可應對 90% 的文本處理需求。