String中的java参数替换

The*_*Guy 2 java regex

我正在寻找一种方法来替换字符串中的变量值.这是我的字符串:

"cp $myfile1 $myfile2"
Run Code Online (Sandbox Code Playgroud)

事实上,我查看了javadoc,似乎我可以使用String类中的split()方法,但是我也看到了一篇文章,似乎可以用regex和replaceAll()替换所有变量方法.不幸的是,我没有找到最后一个解决方案的任何例子.

在我的情况下是否可以使用replaceAll(带示例)?

aio*_*obe 5

不,你不能String.replaceAll在这种情况下使用.(您可以替换所有$...子字符串,但每次替换都取决于要替换的实际变量.)

这是一个同时替换的示例,它取决于要替换的子字符串:

import java.util.*;
import java.util.regex.*;

class Test {
    public static void main(String[] args) {

        Map<String, String> variables = new HashMap<String, String>() {{
            put("myfile1", "/path/to/file1");
            put("myfile2", "/path/to/file2");
        }};

        String input = "cp $myfile1 $myfile2";

        // Create a matcher for pattern $\S+
        Matcher m = Pattern.compile("\\$(\\S+)").matcher(input);
        StringBuffer sb = new StringBuffer();

        while (m.find())
            m.appendReplacement(sb, variables.get(m.group(1)));
        m.appendTail(sb);

        System.out.println(sb.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

cp /path/to/file1 /path/to/file2
Run Code Online (Sandbox Code Playgroud)

(改编自此处:一次替换多个子串)