2

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!

2 Answers 2

4

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.

3
  • Maybe your hash contains a value looking like ${...}? I can't say without knowing your input and your hash content. You may include a debug output or put a break point just in the last line and look for variable and rep each time.
    – Howard
    Sep 3, 2011 at 14:58
  • The loop keeps returning the same regexp match (userName), it doesn't loop trough each match. so if I have "username = '${userName}' and password= = '${password}'" it loops and outputs (debug): variable = ${userName} rep = John Doe so it's correct but just keeps looping and outputing that and never the ${password} one
    – scal
    Sep 3, 2011 at 15:07
  • Stupid me, forgot to type the m.replace() in the code, and they say copy/paste is bad practice! :)
    – scal
    Sep 3, 2011 at 15:09
0

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

1
  • The string can contain 0 to n variables, therefore the reg exp doesn't fit my requirements. Will check the link for help. Thanks
    – scal
    Sep 3, 2011 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.