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.

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

3 Comments

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.
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
Stupid me, forgot to type the m.replace() in the code, and they say copy/paste is bad practice! :)
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 Comment

The string can contain 0 to n variables, therefore the reg exp doesn't fit my requirements. Will check the link for help. Thanks

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.