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 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
精彩评论