Regular Expression - Java: String replacement with ordinal number
仅有的幸福
仅有的幸福 2017-06-30 09:56:29
0
3
996

Original text:

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

with:

片仔癀(<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)等。

Now we can use regular expressions to replace the target text, but the serial number cannot be completed (cannot be looped)

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++;
}

仅有的幸福
仅有的幸福

reply all(3)
刘奇

There are too many problems in your code

        
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)等。
         * */
        
        

Also, is the a tag not ended?

给我你的怀抱

Reference this:
https://stackoverflow.com/que...

Try replacing replaceAll with replaceFirst, only replace the first one each time, and then add up i.

巴扎黑

Change "a" in the tag to ', try it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template