在 java 代码中使用 Regex 动态替换字符串

Replace string dynamically using Regex in java code

我想要 java 代码中的解决方案

字符串 inputStr = "This is a sample @hostname1 @host-name2 where I want to convert the string like :@test host-@test1 to format i.e dollar followed by open braces, string and close braces.";

我需要的输出字符串

输出:"This is a sample ${hostname1} ${host-name2} where I want to convert the string like :${test} host-${test1} to format i.e dollar followed by open braces, string and close braces.";

我在下面试过

public void regEx(String intputStr){
        String pattern = "\S(@)\S+";
         Pattern r = Pattern.compile(pattern);
         Matcher m = r.matcher(commands);

         String replacePattern = " \$\{\S+\} ";
         int i=0;

         while(m.find()) {
             Pattern.compile(pattern).matcher(intputStr).replaceAll(replacePattern);
            // System.out.println(m.group(i));
             //i++;
         }   
        // System.out.println(i);
        System.out.println(intputStr);
    }

但我遇到异常,无法继续。请帮忙

您可以使用以下单行代码:

inputStr = inputStr.replaceAll("@(.*?)\s", "\${} ");

这与正则表达式 @(.*?)\s 匹配,它捕获 at 符号和最近的 space 之间的所有内容,并将其替换为您想要的格式。

String inputStr = "This is a sample @hostname1 @host-name2 where I want to convert the string like :@test host-@test1 to format i.e dollar followed by open braces, string and close braces.";
// add space to match term should it occur as the last word
inputStr += " ";
inputStr = inputStr.replaceAll("@(.*?)\s", "\${} ");
inputStr = inputStr.substring(0, inputStr.length()-1);

System.out.println(inputStr);

输出:

This is a sample ${hostname1} ${host-name2} where I want to convert the string like :${test} host-${test1} to format i.e dollar followed by open braces, string and close braces.