简体   繁体   English

如何用正则表达式替换组的内容

[英]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 这是我想要的替换字符串: 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. 我想用上传到服务器后获得的ID替换字符串中的文件路径,但是我的程序处于无限循环中。

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

You may use Matcher#appendReplacement : 您可以使用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 . 请参阅Java演示

The <[^<>]*> pattern is enough in your case as it will match < , then any 0 or more chars other than < and > and then < . 在您的情况下, <[^<>]*>模式就足够了,因为它将匹配< ,然后匹配<>以外的0个或多个字符,然后匹配<

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM