2

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

0

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Without a return-statement, this method does exactly nothing.
You can't replace them one by one like that. What if you have .put("$myfile1", "$myfile2")?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.