Search code examples
javaregexstringjenkinsreplaceall

Use replaceAll() to replace all occurrences of characters in string


Let's say I have this example string:

String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";

And I want to get this string as a result of a replacement procedure:

String textreplaced =  "**/src/pt/data,**/src/pt/groove";

Basically, what I wanted was to replace all occurrences of characters before the /src with **/. This might be tricky and I've tried to capture groups between the comma and the /src text but it doesn't work as I was expecting.

I was using the replaceAll() method (wihtin Jenkins).

Does anyone have any idea how can I get it?


Solution

  • Use positive lookahead:

    String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";
    
    System.out.println(text.replaceAll("([\\w/]+)(?=/src)", "**")); // **/src/pt/data,**/src/pt/groove