如何提取字符串的特定部分并替换为相同的提取值但大小写不同 - 使用 java

How to extract a particular part of string and replace with the same extracted value but in different case - using java

  1. 我的输入t%60hiag%2Fra%2Cjan
  2. 我希望将其转换为 t%60hiag%2fra%2cjan

我想用 %2f 替换 %2F。即 0-9 之间的任何数字后跟 A-F 的大写字母都应转换为小写字母。

我能够提取并替换为通用字符串。但是我需要帮助将提取的字符串替换为小写。

  private static String urlEncodeLowerCase(String stringInput)
  {
    stringInput = stringInput.replaceAll("%[0-9]{1}[A-F]{1}", "T");  
    return stringInput;
  }

上面的代码将提取并用 "T" 替换提取的字符串,但我想要类似的东西

stringInput = stringInput.replaceAll("%[0-9]{1}[A-F]{1}", "%[0-9]{1}[A-Z]{1}".toLowerCase);  

以上代码无效。这只是为了让您了解我的要求。

您应该使用正则表达式来匹配要更改的字符串部分。之后,您应该遍历所有匹配项并通过转换匹配部分并保持其他所有不变来重建字符串。看看 Pattern、Matcher 和 StringBuilder 类 是如何工作的。

试试这个

private static String urlEncodeLowerCase(String stringInput) {
    Pattern pattern = Pattern.compile("%[0-9]{1}[A-Z]{1}");
    Matcher matcher = pattern.matcher(stringInput);
    while (matcher.find()) {
        String s = matcher.group();
        stringInput = stringInput.replace(s, s.toLowerCase());
    }
    return stringInput;
}

您可以使用 Matcher#appendReplacement。根据 Java Matcher class docs:

The appendReplacement and appendTail methods can be used in tandem in order to collect the result into an existing string buffer

查看此 Java 演示:

String s = "Some Text %0A";
Pattern p = Pattern.compile("%[0-9][A-Z]");
StringBuffer result = new StringBuffer();
Matcher m = p.matcher(s);
while (m.find()) {
    m.appendReplacement(result, m.group().toLowerCase());
}
m.appendTail(result);
System.out.println(result.toString());
// => Some Text %0a

如果要确保大写字母后有单词边界,请使用 "%[0-9][A-Z]\b" 模式。