gpt4 book ai didi

java - 如何使用正则表达式从部分结果替换为完整内容?

转载 作者:行者123 更新时间:2023-11-30 04:08:20 24 4
gpt4 key购买 nike

我有一个正则表达式和替换例程,有几个步骤。它工作正常,我想要的内容已找到并替换。但我不知道如何将部分替换的内容设置回完整内容。

我想划掉某些标签中的数字,这里是“number”和“otherNumber”。

String content = "complex content number="456" with many linebreaks\n
signal number="123" test otherNumber="A1" endsignal\n
more complex content";

结果应该是:

complex content number="456" with many linebreaks\n
signal number="XXX" test otherNumber="XX" endsignal\n
more complex content

请注意,只有特定行中的数字被屏蔽。

对于我想要替换值的行,前面有一个信号词,后面有一个信号词。使用第一个匹配器 signal.*?endsignal,我提取应进行替换的行,因为其他行可能包含相同的标签。

然后,我仅在该行上使用前瞻 (?<=number=").*?(") 运行另一个匹配器,并替换 number 标记的找到内容。

Matcher m = Pattern.compile("signal.*?endsignal").matcher(content);
while (m.find()) {
String match = m.group(1);
match = Pattern.compile("(?<=number=").*?(")").matcher(match).replaceAll("XXX");
}
Sysout(content); //still content has number="123" not masked.

到目前为止一切顺利,替换在我的代码中运行良好(不要指望我在这里的示例,只是为了让我的问题清楚)。

问题:我现在有一个包含替换内容的String match。如何将替换的行放回完整的 String content 变量中?因为它仍然包含旧的未替换的内容。

最佳答案

你不会......直到最后:

    public static void main(String[] args) {
String content = "complex content number=\"456\" with many linebreaks\n" +
"signal number=\"123\" test otherNumber=\"XX\" endsignal\n" +
"more complex content";

Matcher m = Pattern.compile("signal.*?endsignal").matcher(content);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String match = m.group(0); // the whole match... including start/end signal.
match = Pattern.compile("(?<=number=\").*?(\")").matcher(match).replaceAll("XXX");

m.appendReplacement(sb, match);
}
m.appendTail(sb);
content = sb.toString();

System.out.println(content);
}

参见 Javadoc for Matcher

编辑

    private static final Pattern numberpat = Pattern.compile("(?<=number=\")(.+?)(?=\")");
private static final Pattern linepat = Pattern.compile("signal.*?endsignal");

public static void main(String[] args) {
String content = "complex content number=\"456\" with many linebreaks\n" +
"signal number=\"123\" test otherNumber=\"A2\" endsignal\n" +
"more complex content";

Matcher m = linepat.matcher(content);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String match = m.group(0); // the whole match... including start/end signal.
m.appendReplacement(sb, "");
Matcher nmat = numberpat.matcher(match); // note the new regular expression with only one matching group
while (nmat.find()) {
nmat.appendReplacement(sb, nmat.group(0).replaceAll(".", "X"));
}
nmat.appendTail(sb);
}
m.appendTail(sb);
content = sb.toString();

System.out.println(content);
}

使用两个循环。

请注意,正则表达式做了“正确的事情”,并且与 A1 中的 otherNumber="A1" 不匹配,因为它不匹配,因为它在“otherNumber”中查找小写“N”

如果你想匹配任意大小写,我推荐"(?<=[Nn]umber=\")(.+?)(?=\")"

关于java - 如何使用正则表达式从部分结果替换为完整内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com