3 回答
TA贡献1839条经验 获得超15个赞
从 Java 9 开始,有一种Matcher.replaceAll方法将回调函数作为参数:
String text = "<ol start=\"3\">\n\t<li>Element 1</li>\n\t<li>Element 2</li>\n\t<li>Element 3</li>\n</ol>";
String result = Pattern
.compile("<ol start=\"(\\d)\">")
.matcher(text)
.replaceAll(m -> "<ol>" + repeat("\n\t<li style=\"visibility:hidden\" />",
Integer.parseInt(m.group(1))-1));
对于repeat字符串,您可以从这里开始使用技巧,或者使用循环。
public static String repeat(String s, int n) {
return new String(new char[n]).replace("\0", s);
}
之后result是:
<ol>
<li style="visibility:hidden" />
<li style="visibility:hidden" />
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
</ol>
如果您坚持使用旧版本的 Java,您仍然可以分两步进行匹配和替换。
Matcher m = Pattern.compile("<ol start=\"(\\d)\">").matcher(text);
while (m.find()) {
int n = Integer.parseInt(m.group(1));
text = text.replace("<ol start=\"" + n + "\">",
"<ol>" + repeat("\n\t<li style=\"visibility:hidden\" />", n-1));
}
由 Andrea ジーティーオー 更新:
我修改了上面的(很棒的)解决方案,以包含<ol>具有多个属性的内容,以便它们的标签不以start(例如,<ol>带有字母, as <ol start="4" style="list-style-type: upper-alpha;">)结尾。这用于replaceAll整体处理正则表达式。
//Take something that starts with "<ol start=", ends with ">", and has a number in between
Matcher m = Pattern.compile("<ol start=\"(\\d)\"(.*?)>").matcher(htmlString);
while (m.find()) {
int n = Integer.parseInt(m.group(1));
htmlString = htmlString.replaceAll("(<ol start=\"" + n + "\")(.*?)(>)",
"<ol $2>" + StringUtils.repeat("\n\t<li style=\"visibility:hidden\" />", n - 1));
}
TA贡献1829条经验 获得超7个赞
你不能使用正则表达式来做到这一点,或者即使你找到了一些技巧来做到这一点,这也将是一个次优的解决方案..
正确的方法是使用 HTML 解析库(例如Jsoup),然后将<li>
标记作为子项添加到<ol>
,特别是使用Element#prepend方法。(使用 Jsoup,您还可以读取start
属性值以计算要添加的元素数量)
添加回答
举报