scal
scal

Reputation: 23

Java: replace multiple string patterns from one string value

I'm struggling to get this working.

I have a regex pattern as: ".*(${.*}).*"

And a string variable myVar = "name = '${userName}' / pass = '${password}'"

I have a hashmap which stores values, in this case "${userName}" would have a value of "John Doe" and "${password}" would have a value of "secretpwd".

How can I loop all found matches in myVar (in this case "userName" and "password")? Then I could loop each match found and request their corresponding value from the hashmap.

Thanks!

Upvotes: 2

Views: 1986

Answers (2)

Tristan
Tristan

Reputation: 9111

With this string as regexp, you'll have 2 groups containing "${user}" and "${password}" :

".*(\\$\\{.*}).*(\\$\\{.*}).*"

To iterate through the groups :

// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();

if (matchFound) {
    // Get all groups for this match
    for (int i=0; i<=matcher.groupCount(); i++) {
        String groupStr = matcher.group(i);
    }
}

source : http://www.exampledepot.com/egs/java.util.regex/Group.html

Upvotes: 0

Howard
Howard

Reputation: 39187

You can use e.g. the following code:

Pattern p = Pattern.compile("\\$\\{.*?\\}");
while (true) {
    Matcher m = p.matcher(myVar);
    if (!m.find()) {
        break;
    }
    String variable = m.group();
    String rep = hash.get(variable);
    myVar = m.replaceFirst(rep);
}

Note that I adjusted the regular expression to fit your requirements.

Upvotes: 4

Related Questions