I know I shouldn't do your work for you, but that exercise you propose was so interesting to me that I just couldn't resist:
This method receives your two strings and gives you back a Map
(ok, just change the return type if you REALLY want a HashMap
instead):
public static Map<String, String> getMap(String regStr, String originalString) {
Pattern searchPattern = Pattern.compile("%\\{([^}]+)\\}");
Matcher matcher = searchPattern.matcher(regStr);
StringBuilder builder = new StringBuilder();
List<String> keys = new LinkedList<>();
Map<String, String> map = new HashMap<>();
int start = 0;
while(matcher.find()) {
builder.append(Pattern.quote(regStr.substring(start, matcher.start())))
.append("(.+)");
start = matcher.end();
keys.add(matcher.group(1));
}
builder.append(Pattern.quote(regStr.substring(start)));
Pattern finalPattern = Pattern.compile(builder.toString());
matcher = finalPattern.matcher(originalString);
int pos = 0;
if(!matcher.find()) {
throw new RuntimeException("regStr and originalString don't match");
}
for(String key: keys) {
map.put(key, matcher.group(++pos));
}
return map;
}
Some light testing:
public static void main(String[] args) {
// Original requirement
System.out.println(getMap("%{orgCity} to %{destCity}", "delhi to goa"));
// A variation with two words values
System.out.println(getMap("%{orgCity} to %{destCity}", "New York to Mexico"));
// Another variation
System.out.println(getMap("%{orgCity} to %{destCity} and more", "delhi to goa and more"));
// order of words doesn't matter
System.out.println(getMap("%{orgCity} %{destCity} to", "delhi goa to"));
// different strings than the original requirement
System.out.println(getMap("I'm going to %{firstCity} and then to %{secondCity}", "I'm going to Nauru and then to Seattle"));
// more than two values, with more than one word
System.out.println(getMap("I am %{age} years old, I have %{eyesColour} eyes and %{pocketContent} in my pocket",
"I am 20 years old, I have dark blue eyes and two coins in my pocket"));
// etc ...
}