TheFrenchGuy
TheFrenchGuy

Reputation: 233

java parameter replacement in a String

I'ms looking for a way to replace my variables in a string by their value. Here is my string lookalike:

"cp $myfile1 $myfile2"

In fact, I looked the javadoc and it seems that I could use split() method from String class which is good but I have also seen an article on which it seems that it is possible to replace all my variables with regex and replaceAll() method. Unfortunately I didnt find any example on the last solution.

Is it possible to use replaceAll in my case (with an example)?

Upvotes: 2

Views: 4094

Answers (2)

flash
flash

Reputation: 6810

I would stick to java and use

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

You could even do multiple replacements with this approach:

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

You could use it like this:

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

Upvotes: 1

aioobe
aioobe

Reputation: 420951

No, you can't use String.replaceAll in this case. (You could replace all $... substrings, but each replacement would depend on the actual variable being replaced.)

Here's an example that does a simultaneous replacement which depends on the substring being replaced:

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

Output:

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

(adapted from over here: Replace multiple substrings at once)

Upvotes: 5

Related Questions