开发者

Java: replace multiple string patterns from one string value

开发者 https://www.devze.com 2023-04-02 20:25 出处:网络
I\'m struggling to get this working. I have a regex pattern as: \".*(${.*}).*\" And a string variable myVar = \"name = \'${userName}\' / pass = \'${password}\'\"

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 ha开发者_开发知识库ve 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!


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号