0

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
}
7
  • Do you need regex for that? You could just string-replace yes; with no; and auto; with manual;. Commented Aug 30, 2016 at 3:08
  • I dont think its that simple. Since there can be multiple lines containing "yes" and "auto". The text provided at the top is read from a file. Commented Aug 30, 2016 at 3:10
  • I need to replace the yes and auto only if its within the matching options { block. Commented Aug 30, 2016 at 3:12
  • See Matcher.appendReplacement(). FYI: The reason your code is not working, is because String.replaceAll() returns the updated value. It does not modify the input string. Read the javadoc!! Commented Aug 30, 2016 at 3:14
  • @DennySutedja JavaScript is not Java. Commented Aug 30, 2016 at 3:14

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.