素材牛VIP会员
Java:字符串替换带序号
 想***儿  分类:Java代码  人气:1320  回帖:3  发布于6年前 收藏

原文本:

片仔癀(<span label="粉色背景" >603567</span>.SH)、
天士力(<span label="绿色背景" >600535</span>.SH)、
片仔癀(<span label="粉色背景" >603567</span>.SH)
和昆药集团(<span label="金色背景" >600422</span>.SH)等。

替换成:

片仔癀(<span label="粉色背景" ><a link="http://#link?index=1">603567</a></span>.SH)、
天士力(<span label="绿色背景" ><a link="http://#link?index=2">600535</a></span>.SH)、
片仔癀(<span label="粉色背景" ><a link="http://#link?index=3">603567</a></span>.SH)
和昆药集团(<span label="金色背景" ><a link="http://#link?index=4">600422</a></span>.SH)等。

现利用正则表达式可以替换到目标文本,就是序号那一块无法完成(无法循环)

Pattern pattern = Pattern.compile("(<span.*?label=\"(*色背景)\".*?>)(.*?)(</span>)");
Matcher matcher = pattern.matcher(str);
int i=0;
while (matcher.find()) {
    System.out.println(matcher.replaceAll(matcher.group(1) + "<a link=\"http://#link?index="+i+"\">" + matcher.group(3) + "</a>" + matcher.group(4)));
    i++;
}

讨论这个帖子(3)垃圾回帖将一律封号处理……

Lv1 新人
闪***星 UI设计师 6年前#1
public static String  formatHtml(String input){
        Matcher m=Pattern.compile("[^><]+(?=</span>)").matcher(input);
        StringBuffer result=new StringBuffer();
        String url="<a link=\"http://#link?index={0}\">{1}</a>";
        int count=1;
        while(m.find()){
            m.appendReplacement(result,MessageFormat.format(url, count,"$0"));            
            count++;
        }
        m.appendTail(result);
        return result.toString();
    }
Lv6 码匠
雨***技 其它 6年前#2

参考这个:
https://stackoverflow.com/que...

试着把replaceAll换成replaceFirst,每次只替换第一个,然后累加i

Lv3 码奴
销***表 PHP开发工程师 6年前#3

你的代码里面问题太多了

        
String str="片仔癀(<span label=\"粉色背景\" >603567</span>.SH)、"+
        "天士力(<span label=\"绿色背景\" >600535</span>.SH)、"+
        "片仔癀(<span label=\"粉色背景\" >603567</span>.SH)"+
        "和昆药集团(<span label=\"金色背景\" >600422</span>.SH)等。";

String patternStr="(<span\\s+label=\\\".色背景\\\"\\s*>)(\\d+)";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(str);
String strResult=str;
int i=0;
while (matcher.find()) {
    i++;
    String replaceTo=matcher.group(1)+
            "<a link=\"http://#link?index="+i
            +"\">"+matcher.group(2)+"</a>";
    strResult=strResult.replaceFirst(patternStr, replaceTo);
}

System.out.println(strResult);

        
        /*    输出:
片仔癀(<span label="粉色背景" ><a link="http://#link?index=1">603567</a></span>.SH)、天士力(<span label="绿色背景" ><a link="http://#link?index=2">600535</a></span>.SH)、片仔癀(<span label="粉色背景" ><a link="http://#link?
index=3">603567</a></span>.SH)和昆药集团(<span label="金色背景" ><a link="http://#link?index=4">600422</a></span>.SH)等。
         * */
        
        

还有 a 标签是不是没有结束啊

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取