需求:匹配目標文本中的 "hello" 變體,包含任意位置插入空格(如 "hel lo", "he llo", "hell o"),並輸出**原始含空格文本**,而非去除空格後的 "hello"。
h\s*e\s*l\s*l\s*o
或更簡潔(允許字符間任意空白):
h\s*e\s*l\s*l\s*o
若需匹配 "hello" 任意字符間可有空格:
h\s*e\s*l\s*l\s*o
String regex = "h\\s*e\\s*l\\s*l\\s*o"; // 雙重轉義
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println("匹配到: [" + m.group() + "]"); // 輸出原文含空格
}
public static String toSpacedRegex(String keyword) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyword.length(); i++) {
char c = keyword.charAt(i);
if (i > 0) sb.append("\\s*");
sb.append(Pattern.quote(String.valueOf(c))); // 轉義特殊字符
}
return sb.toString();
}
// 使用
String regex = toSpacedRegex("hello"); // h\s*e\s*l\s*l\s*o
`replaceAll` 修改的是**副本**,且輸出時已失去原始空格位置信息。正則引擎直接在原文匹配,`m.group()` 保留原貌,滿足「輸出含空格原文」需求。
掌握 `\s*`「零或多個空白字符」插入字符間,即可靈活應對各類「變體關鍵字匹配並保留原文」場景。