[英]How to replace a string with another string using regex?
從文件輸入文本:
someother block {
enable route yes;
dhcp auto;
....
}
options {
dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.