gpt4 book ai didi

java - Android Java 正则表达式替换重复模式如图所示

转载 作者:行者123 更新时间:2023-12-01 13:35:49 25 4
gpt4 key购买 nike

我有以下 bbcodes,例如 [369] 需要转换为 <img src ...http// />

但是当涉及到替换多个项目时,例如

 [369] [369] [369] [369]

,变成如下替换后的字符串1,2,3,4个token,总共分别为10个。

<img src ...http// />   <img src ...http// /><img src ...http// />  <img src ...http// /><img src ...http// /><img src ...http// />   <img src ...http// /><img src ...http// /><img src ...http// /><img src ...http// />

输入

班仔比人陰返轉頭[369] [369] [369] <br/>BTW大家入黎咩都傾下,我地好warm的#yup# #yup# #yup#

我想实现字符串替换并提供期望的输出:

班仔比人陰返轉頭<img src ...http// /> <img src ...http// /><img src ...http// />  <br/>BTW大家入黎咩都傾下,我地好warm的<img src ...http// /><img src ...http// /><img src ...http// />

但是到了执行的时候..实际输出:

班仔比人陰返轉頭<img src ...http// />       <img src ...http// /><img src ...http// />  
<img src ...http// /><img src ...http// /><img src ...http// /> <br/>BTW大家入黎咩都傾下,我地好warm的<img src ...http// /> <img src ...http// /><img src ...http// />
<img src ...http// /><img src ...http// /><img src ...http// />

请帮我看看是否有while循环导致重复替换的情况发生?

下面是我的代码:

public String replace(String text , String bbcode , String imageLocation ){


StringBuffer imageBuffer = new StringBuffer ("");
Pattern pattern = Pattern.compile(Pattern.quote(bbcode));
Matcher matcher = pattern.matcher(text);

StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {


imageBuffer.append("<img src=\"" + imageLocation + "\" />");
String replacement = imageBuffer.toString();
builder.append(text.substring(i, matcher.start()));

if (replacement == null) {
builder.append(matcher.group(0));
break;
} else {
builder.append(replacement);
}

i = matcher.end();
}

builder.append(text.substring(i, text.length()));
return builder.toString();
}

最佳答案

如果我理解你的意思,你需要用字符串替换所有出现的模式,所以你可以简单地这样做:

public String replace(String text , String bbcode , String imageLocation ){
return text.replaceAll(Pattern.quote(bbcode), "<img src=\"" + imageLocation + "\" />");
}

希望有帮助。

关于java - Android Java 正则表达式替换重复模式如图所示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21286129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com