正則表達式是一種強大的文本模式匹配工具,其運作原理類似於編譯器處理源代碼:通過識別特定模式將文本轉換為結構化數據。在 Java 中,java.util.regex 包提供了完整的正則表達式支持,核心類包括 Pattern(編譯後的模式)和 Matcher(執行匹配操作的引擎)。
模式是字符序列的文本表示。最簡單的模式如 car 精確匹配該字符串。若需匹配以 c 開頭、以 r 結尾的任意字符串,可使用 c.*r(其中 .* 代表任意數量字符)。
?:0 或 1 次*:0 次或多次+:1 次或多次{n,m}:n 到 m 次[aeiou] 匹配任一元音。預定義簡寫:
\d:數字 [0-9]\w:單詞字符 [a-zA-Z0-9_]\s:空白字符\p{Alpha}(字母)、\p{Alnum}(字母數字)。[A-Z] 匹配大寫字母,[^0-9] 匹配非數字。Pattern pattern = Pattern.compile("\\p{Alnum}+@\\w+\\.\\p{Alpha}{2,3}");(注意雙重轉義)Matcher matcher = pattern.matcher(input);matcher.matches():整個序列完全匹配matcher.find():查找子序列匹配matcher.group():獲取匹配內容import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.*;
public class LongestWordFinder {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("請提供文件路徑");
return;
}
// 內存映射文件讀取
FileInputStream input = new FileInputStream(args[0]);
FileChannel channel = input.getChannel();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
// 解碼為字符緩衝區
CharBuffer charBuffer = Charset.forName("ISO-8859-1").newDecoder().decode(buffer);
// 編譯模式:行分隔符、單詞分隔符
Pattern linePattern = Pattern.compile(".*$", Pattern.MULTILINE);
Pattern wordPattern = Pattern.compile("[\\p{Punct}\\s]+");
Matcher lineMatcher = linePattern.matcher(charBuffer);
String longest = "";
while (lineMatcher.find()) {
String line = lineMatcher.group();
String[] words = wordPattern.split(line);
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
}
System.out.println("最長單詞: " + longest);
input.close();
}
}
Pattern.CASE_INSENSITIVE 等標誌位Pattern.COMMENTS 提高可讀性