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

时间:2016-08-30 03:04:38

标签: java regex

从文件输入文字:

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

我想替换所有"是"和"汽车" 选项 中的文字 与" no"和"手册"分别。

我该如何做到这一点?

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

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
}

1 个答案:

答案 0 :(得分:1)

我认为只需更换功能即可完成!

    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);