java如何在同一个句子中分别替换同一个单词但大小写不同?
例如,替换“如何使用Matcher替换同一句子中的不同方式?”用“LOL,我是否在同一句话中替换不同的LOL?”
如果所有的大写字母都是“HOW is all caps”,则将其替换为LOL。否则,将其替换为LOL
我只知道如何找到它们:
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");
}
但我不知道如何使用matcher和pattern来替换它们
# 1 楼答案
这里有一种方法可以实现你的目标:(不一定是最有效的,但它是有效的,而且简单易懂)
替换所有大写字母,然后重复每个单词,并将剩余的“how”替换为“lol”。末尾的子字符串只是为了删除额外的空间
# 2 楼答案
我想出了一个非常愚蠢的解决方案: