gpt4 book ai didi

java - 如何使用正则表达式将一个字符串替换为另一个字符串?

转载 作者:行者123 更新时间:2023-12-01 09:33:18 25 4
gpt4 key购买 nike

从文件中输入文本:

someother block {
enable route yes;
dhcp auto;
....
}
options {
dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;
.....
}

我想替换选项 block 中的所有“yes”和“auto”文本分别为“否”和“手动”。

我怎样才能做到这一点?

这是我的执行,但文本没有被替换。

String dataPattern  = "\noptions \\{\\s*\n(dnssec-[a-z]+ ([a-z]+));";
Pattern filePattern = Pattern.compile(dataPattern, Pattern.DOTALL);
Matcher filePatternMatcher = filePattern.matcher(input);
if(filePatternMatcher.find()){
System.out.println("0 - "+filePatternMatcher.group(0)); //0 - \ndnssec-enable yes;
System.out.println("1 - "+filePatternMatcher.group(1)); //1 - dnssec-enable yes

System.out.println("2 - "+filePatternMatcher.group(2)); //2 - yes
String value = filePatternMatcher.group(2);
value.replaceAll("\ndnssec-enable ([a-z]+);", "$1somethingelse");
System.out.println("new replaced text:"+value); \\ new-replaced text: yes
}

最佳答案

我想你只需使用替换功能就可以完成它!

    String test="someother block {" +
" enable route yes;" +
" dhcp auto;" +
" ...." +
"}" +
"options { " +
" dnssec-enable yes;" +
" dnssec-validation yes;" +
" dnssec-lookaside auto;" +
" ....." +
"}";

String result;

int opStartIndex=test.indexOf("options");
int opEndIndex=opStartIndex+ test.substring(opStartIndex).indexOf("}");
result=test.substring(0,opStartIndex)+test.substring(opStartIndex, opEndIndex).replace("yes","no").replace("auto","manual")+test.substring(opEndIndex);
System.out.println(result);

关于java - 如何使用正则表达式将一个字符串替换为另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39218153/

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