从文件中输入文本:
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/