我的要求是,我有一個給定的字符串像 String originalString = "delhi to goa";
字符串匹配找到在Java中的鍵值
而且我有一個字符串 String regStr = "%{orgCity} to %{destCity}";
給定的文本可以是任何格式。 (不僅是「德里飛往果阿」,也可以是「新德里果阿」)
現在,由於這兩個字符串,我想用鍵值對一個HashMap作爲
orgCity - >德令哈
DESTCITY - >果阿
這裏關鍵是%{和}內的字符串。值是originalString中的對應字符串。
這需要使用一些正則表達式/模式來實現。
我找不到解決方案。
有人可以幫忙嗎?
感謝
更新
解決方案:
public static void main(String[] args) {
// Original requirement
System.out.println(getValueMap("%{orgCity} to %{destCity}", "delhi to goa"));
// A variation with two words values
System.out.println(getValueMap("%{orgCity} to %{destCity}", "New York to Mexico"));
// Another variation
System.out.println(getValueMap("%{orgCity} to %{destCity} and more", "delhi to goa and more"));
// order of words doesn't matter
System.out.println(getValueMap("%{orgCity} %{destCity} to", "delhi goa to"));
// different strings than the original requirement
System.out.println(getValueMap("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(getValueMap("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 ...
}
public static Map<String, String> getValueMap(String format, String text) {
Map<String, String> map = new HashMap<String, String>();
String pattern = format;
String[] keyList = StringUtils.substringsBetween(format, "%{", "}");
for (String str : keyList) {
pattern = pattern.replaceAll("\\%\\{" + str + "\\}", ("(.+)"));
}
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if(!m.find()) {
throw new RuntimeException("regStr and originalString don't match");
}
for (int i = 0; i < m.groupCount(); i++) {
map.put(keyList[i], m.group(i+1));
}
return map;
}
謝謝摩根!它真的幫了我...我自己也找到了解決這個問題的辦法。將在這裏發佈我寫的代碼。 – pankaj