如何分别替换同一句话中不同大小写的同一个词?
How do I replace the same word but different case in the same sentence separately?
例如,将 "HOW do I replace different how in the same sentence by using Matcher?" 替换为 "LOL do I replace different lol in the same sentence?"
如果 HOW 全部大写,请将其替换为 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");
}
但我不知道如何使用匹配器和模式来替换它们。
这是实现您的目标的一种方法:(不一定是最有效的,但它有效并且易于理解)
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
替换所有大写字母,然后遍历每个单词并将剩余的 "how" 替换为 "lol"。最后的子字符串只是删除多余的 space.
我想出了一个非常愚蠢的解决方案:
String result = source;
result = result.replaceAll(old_Word, new_Word);
result = result.replaceAll(old_Word.toUpperCase(),
newWord.toUpperCase());
例如,将 "HOW do I replace different how in the same sentence by using Matcher?" 替换为 "LOL do I replace different lol in the same sentence?"
如果 HOW 全部大写,请将其替换为 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");
}
但我不知道如何使用匹配器和模式来替换它们。
这是实现您的目标的一种方法:(不一定是最有效的,但它有效并且易于理解)
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
替换所有大写字母,然后遍历每个单词并将剩余的 "how" 替换为 "lol"。最后的子字符串只是删除多余的 space.
我想出了一个非常愚蠢的解决方案:
String result = source;
result = result.replaceAll(old_Word, new_Word);
result = result.replaceAll(old_Word.toUpperCase(),
newWord.toUpperCase());