Search code examples
javaregexreplaceall

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


  1. My Input t%60hiag%2Fra%2Cjan
  2. I want this to be converted to t%60hiag%2fra%2cjan

I would like to replace %2F with %2f. i.e. any number between 0-9 followed by upper case alphabet from A-F should be converted to lower case alphabet.

I was able to extract and replace with a generic string. But I need help in replacing the extracted string to lower case.

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

Above code will extract and replace the extracted string with "T" but I want something similar

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

Above code won't work. This is just to make you understand my requirement.


Solution

  • try this

    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;
    }