Android中忽略空格与大小写替换字符串中的指定单词
Hey there, let's sort out this string replacement issue you're facing!
Your current code converts the entire string to lowercase and strips out all spaces, which doesn't align with your goal—you just want to target any variation of "love" (regardless of capitalization or spaces between its letters) and replace it with "hate", while leaving the rest of the string's original formatting intact.
The Fix: Use a Targeted Regular Expression
Java's String.replaceAll() method supports regex patterns, which lets us match exactly the variants of "love" you care about without modifying other parts of the string. Here's the solution:
// Test case 1: "Love is rare" String a = "Love is rare"; a = a.replaceAll("(?i)l\\s*o\\s*v\\s*e", "hate"); System.out.println(a); // Output: hate is rare // Test case 2: "l o v e is rare" a = "l o v e is rare"; a = a.replaceAll("(?i)l\\s*o\\s*v\\s*e", "hate"); System.out.println(a); // Output: hate is rare // Test case 3: "LO VE is rare" a = "LO VE is rare"; a = a.replaceAll("(?i)l\\s*o\\s*v\\s*e", "hate"); System.out.println(a); // Output: hate is rare
Breakdown of the Regex Pattern
Let's break down (?i)l\\s*o\\s*v\\s*e so you understand how it works:
(?i): Enables case-insensitive matching, so it will matchL,l,O,o, etc.\\s*: Matches 0 or more whitespace characters (spaces, tabs, etc.). If you only want to match spaces (not tabs), replace this with*(a space followed by an asterisk).l\\s*o\\s*v\\s*e: Matches the sequence of letters l → o → v → e, with any number of whitespaces (including zero) between each letter.
Optional: Match Only Standalone "love" Words
If you want to avoid replacing instances where "love" is part of a longer word (like "lover" or "beloved"), you can add word boundaries to the regex:
a = a.replaceAll("(?i)\\bl\\s*o\\s*v\\s*e\\b", "hate");
The \\b ensures that the matched pattern is surrounded by non-word characters (like spaces, punctuation, or the start/end of the string), so it won't touch longer words.
This approach keeps your original string's formatting (other spaces, capitalization of other words) completely intact—only the targeted "love" variants get replaced.
内容的提问来源于stack exchange,提问作者Genie

