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++;
}
There are too many problems in your code
Also, is the a tag not ended?
Reference this:
https://stackoverflow.com/que...
Try replacing
replaceAll
withreplaceFirst
, only replace the first one each time, and then add upi
.Change "a" in the tag to ', try it