Search code examples
javaregexstringreplaceall

how to replace all occurrences of a string inside tags <> using regex in java


I have a string inside tags. Eg: "<abc~a>I am src scr customer<abc~b>"

I want to replace "src" with "abc". I used following regex to replace:- replacAll("(<abc~a>.?)src(.?<abc~b>)"),"$1"+"abc"+"$2"); But it is replacing only first occurrence of string i.e. output is "<abc~a>I am abc src customer<abc~b>"

I want output as "<abc~a>I am abc abc customer<abc~b>".

I don't want to use matcher pattern. Is there any solution using replaceAll() ? Please help.


Solution

  • We can try using a formal regex pattern matcher here. Match on the pattern <abc~a>(.*?)<abc~a>, and for each match append the tag with src replaced by abc. Here is a sample code:

    String input = "Here is a src <abc~a>I am an src customer<abc~b> also another src here.";
    Pattern p = Pattern.compile("<abc~a>(.*?)<abc~b>");
    Matcher m = p.matcher(input);
    StringBuffer buffer = new StringBuffer();
      
    while(m.find()) {
        String replace = "<abc~a>" + m.group(1).replaceAll("\\bsrc\\b", "abc") + "<abc~b>";
        m.appendReplacement(buffer, replace);
    }
    m.appendTail(buffer);
    
    System.out.println(buffer.toString());
    

    This prints:

    Here is a src <abc~a>I am an abc customer<abc~b> also another src here.

    Note that in many other languages we could have used a regex callback function. But core Java does not support this functionality, so we have to iterate over the entire input.