使用正则表达式替换符合规则的字符串

现有一个 SVG 文件,文本内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 120 120" enable-background="new 0 0 120 120" xml:space="preserve">
<g id="ry" transform="scale(1,1)">
<g>
<g>
<defs>
<rect id="SVGID_1_" class='cut' width="120" height="120"/>
</defs>
<clipPath id="SVGID_2_" class="wonAd">
<use xlink:href="#SVGID_1_" overflow="visible"/>
</clipPath>
<g clip-path="url(#SVGID_2_)">
<polygon fill="#D2E9F5" points="0,0 309.4,0 309.2,120.4 0,120.4 "/>
<path fill="#B6CB7E" d="M0,88.2c0,0,30.6,1.1,33.9,4c3.1,2.8,40.2-4,40.2-4s13.4-9.2,39-5.9c25.4,3.1,24.7,4.4,31.1,4.4
c6.4,0,7.5-2.1,19.7,0.7c6.8,1.6,9.2,2.4,10.8,2.8c2.4,0.7,2.8,0.7,12.7,4.7c20,7.7,22.3,8.9,22.3,8.9s52.4-10.3,71.3-13.4
c18.3-3.1,24.2-2.4,28.2-2.4l0,0c0,0.5,0.1,1.2,0,2.4c-0.2,3,0.1,8.6,0,14.3c-0.5,8,0,15.5,0,15.5H0V88.2L0,88.2z"/>
<path fill="#7C9330" d="M0,103.9c0,0,14.6-2.4,28.7-15.5C42.5,75.2,68.4,78,72,87.9c4,6.3,12.2,15.5,25.9,16
c14.3,0.7,33.9-7.3,39.7-8.7c4.7-1.1,6.3-2.1,9.9-2.8c4-0.7,10.6-1.4,27.3,2.1c31.8,6.3,39.3,4.4,56-4
c16.7-8.2,31.1-14.6,51.2,1.1c20.2,16,22.6,9.9,27.1,12.2l0,0v0.5c0,0.7,0,2.1,0,3.5c0.5,4.7,0,12.2,0,12.2L0,120.4V103.9
L0,103.9L0,103.9z"/>
<path fill="#F8FCFE" d="M60,19.7c0,0,0.5-7.3,9.2-7.5c8.7-0.5,9.4,9.4,9.2,10.8c-0.7,1.6,3.5-4.7,7.3,1.6
c3.1,5.9-5.9,6.3-2.4,5.9c4,0-27.5,0-27.5,0s-5.1-1.2-4.7-5.9C51.3,19.7,56,17.2,60,19.7z"/>
</g>
</g>
</g>
<g>
<g>
<defs>
<rect id="SVGID_3_" class='cut' width="120" height="120"/>
</defs>
<clipPath id="SVGID_4_" class="wonAd">
<use xlink:href="#SVGID_3_" overflow="visible"/>
</clipPath>
<g clip-path="url(#SVGID_4_)" class="layoutImgWrap"></g>
</g>
</g>
</g>
</svg>

需要对它以 SVGID_ 开头的 id 属性值进行重置,以一个 UUID 替换,代码实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public String renewSvgId(String source) {
String target = source;
Matcher matcher = Pattern.compile("(id=\"SVGID_\\d+_\")").matcher(target);
while (matcher.find()) {
// 匹配到的字符串
String matched = matcher.group(1);
// 原 id 属性值
String idAttr = matched.replaceAll("\"", "").split("=")[1];
// 新 id 属性值
String newId = UUID.randomUUID().toString();
// 设置新的 id 属性,并替换原 id 属性的引用
target = target.replaceFirst("id=\"SVGID_\\d+_\"", String.format("id=\"%s\"", newId))
.replaceAll(idAttr, newId);
}
return target;
}

使用正则表达式替换符合规则的字符串
https://blog.yohlj.cn/posts/2cea1092/
作者
Enoch
发布于
2016年12月9日
许可协议