2

I have a string where I have to replace it with a substring. For eg, "Servicing" is the word. I have a substring as "servi". Now, i need to check if "Servicing" has "servi". If yes, then i need to replace it with "servicing". When i try to replace, it is getting displayed as "servi". But the expected output is "Servicing"Can you please help me in resolving this ? Please find the code below.

String stringValue = "Servicing";
if (stringValue != null && stringValue != "") {
    i = stringValue.toLowerCase().indexOf("servi", i+1);
    if(i>=0){
        newData = stringValue .replaceAll("(?i)"+"servi", "<mark>"+"servi"+"</mark>");
        System.out.println(newData); // Case sensitive should remain same as String. Not as substring.
        i = -1;
        }
    }
Kutty
  • 712
  • 1
  • 5
  • 22

1 Answers1

6

Use

String stringValue = "Servicing";
if (stringValue != null && !stringValue.isEmpty()) {
     String newData = stringValue.replaceAll("(?i)servi", "<mark>$0</mark>");
     System.out.println(newData);
}

See the Java demo

Details:

  • (?i) - case insensitive inline modifier
  • servi - a literal char sequence
  • $0 - a backreference to the whole match value. It makes sure you insert the servi with the matched case (no need to hardcode it inside the replacement as in the original code).
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563