Grapes
Grapes

Reputation: 251

How to replace the contents of a group with a regular expression

This is the original string:

233<C:\Users\Grapes\Documents\title.png>233<C:\Users\Grapes\Documents\title.png>33

This is the replaced string I want: 233<1>233<2>33

I want to replace the file path in the string with the id I got after uploading to the server, but my program is in an infinite loop.

public void sendMessage(String msg) {
    new Thread(()-> {
        var pat = Pattern.compile("<(.*?[^\\\\])>");
        var matcher = pat.matcher(msg);
        int k = 0;
        while (matcher.find()) {
            matcher.replaceFirst("<" + k++ + ">"));
        }
        System.out.println(msg);
    }).start();
}

Upvotes: 1

Views: 60

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use Matcher#appendReplacement:

String s = "233<C:\\Users\\Grapes\\Documents\\title.png>233<C:\\Users\\Grapes\\Documents\\title.png>33";
int k = 0;
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("<[^<>]*>").matcher(s);
while (m.find()) {
    m.appendReplacement(result, "<" + ++k + ">");
}
m.appendTail(result);
System.out.println(result.toString());
// => 233<1>233<2>33

See the Java demo.

The <[^<>]*> pattern is enough in your case as it will match <, then any 0 or more chars other than < and > and then <.

Upvotes: 5

Related Questions