2

我正在寻找一种方法来用它们的值替换字符串中的变量。这是我的字符串相似:

"cp $myfile1 $myfile2"

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

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

4

2 回答 2

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

输出:

cp /path/to/file1 /path/to/file2

(改编自这里:一次替换多个子字符串

于 2012-05-07T12:45:05.037 回答
1

我会坚持使用 java 并使用

public void replace(String s, String placeholder, String value) {
    return s.replace(placeholder, value);
}    

您甚至可以使用这种方法进行多次替换:

public String replace(String s, Map<String, String> placeholderValueMap) {
  Iterator<String> iter = placeholderValueMap.keySet().iterator();
    while(iter.hasNext()) {
        String key = iter.next();
        String value = placeholderValueMap.get(key);
        s = s.replace(key, value);
    }
    return s;
}

你可以像这样使用它:

String yourString = "cp $myfile1 $myfile2";
Map<String, String> placeholderValueMap = new HashMap<String, String>();
placeholderValueMap.put("$myfile1", "fileOne");
placeholderValueMap.put("$myfile2", "fileTwo");

someClass.replace(yourString, placeholderValueMap);
于 2012-05-07T12:48:46.643 回答