Reputation: 95
For example, replace "HOW do I replace different how in the same sentence by using Matcher?" with "LOL do I replace different lol in the same sentence?"
If HOW is all caps, replace it with LOL. Otherwise, replace it with lol.
I only know how to find them:
String source = "HOW do I replace different how in the same " +
"sentence by using Matcher?"
Pattern pattern = Pattern.compile(how, Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(source);
while (m.find()) {
if(m.group.match("^[A-Z]*$"))
System.out.println("I am uppercase");
else
System.out.println("I am lowercase");
}
But I don't know how to replace them by using matcher and pattern.
Upvotes: 0
Views: 225
Reputation: 95
I came up with a really dumb solution:
String result = source;
result = result.replaceAll(old_Word, new_Word);
result = result.replaceAll(old_Word.toUpperCase(),
newWord.toUpperCase());
Upvotes: 0
Reputation: 676
Here's one way to achieve your goal: (not necessarily the most efficient, but it works and is simply understood)
String source = "HOW do I replace different how in the same sentence by using Matcher?";
String[] split = source.replaceAll("HOW", "LOL").split(" ");
String newSource = "";
for(int i = 0; i < split.length; i++) {
String at = split[i];
if(at.equalsIgnoreCase("how")) at = "lol";
newSource+= " " + at;
}
newSource.substring(1, newSource.length());
//The output string is newSource
Replace all uppercase, then iterate over each word and replace the remaining "how"s with "lol". That substring at the end is simply to remove the extra space.
Upvotes: 2