String line = "\"string\": \"Hello World\",";
Matcher m = Pattern.compile("\"(.*)\"\\s?:\\s?\"\\w\"\\s?,?").matcher(line);
目標是從 "string": "Hello World", 中提取鍵值,但正則無法匹配。
"(.*)" 中的 .* 是貪婪模式,會盡可能多地匹配字符。World" 後的引號),導致後續的 \s?:\s?"\w" 無法匹配剩餘內容。在量詞後加 ? 開啟懶惰模式:
Pattern.compile("\"(.*?)\"\\s*:\"\\s*(.*?)\",?")
(.*?):非貪婪匹配任意字符,遇到下一個雙引號即停止。\\s*:匹配任意空白(含 0 個),比 \\s? 更健壯。String line = "\"string\": \"Hello World\",";
Pattern p = Pattern.compile("\"(.*?)\"\\s*:\"\\s*(.*?)\",?");
Matcher m = p.matcher(line);
if (m.find()) {
System.out.println("Key: " + m.group(1)); // string
System.out.println("Value: " + m.group(2)); // Hello World
}
正則失敗是因為 .* 貪婪吞噬了後續結構。改用 .*? 即可精準提取鍵值對。實際項目中**強烈建議使用 JSON 解析庫**。