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

标签 java regex

从文件中输入文本:

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/

相关文章:

java - AWS SES 交付时间很长

php - 在 Laravel 验证正则表达式规则中验证纬度/经度 - preg_match() : No ending delimiter '/' found

regex - 什么正则表达式可用于在 Google App Engine 仪表板中查找长时间运行的 url?

java - 获取 ArrayIndexOutOfBoundsException : 2 When I use different delimiters for splitting strings

java - 如何在另一个 Controller 中覆盖@RequestMapping?

java - JPA调用存储过程从2 db中选择数据

python - 提高 C++ 正则表达式替换性能

c# - 在 C# 中使用正则表达式匹配多行

java - 验证java中的引用代码

java - 合并两个相对文件 URL