简体   繁体   中英

How to replace a string with another string using regex?

INPUT TEXT FROM FILE :

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

I would like to replace all the "yes" and "auto" text in options block ONLY with "no" and "manual" respectively.

How can I accomplish this?

Here is my execution but the text is not replaced.

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
}

I think you could complete it with just Replace function!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM