निम्न प्रपत्र के चर को बदलता है <<VAR>>, जिसमें मान एक मानचित्र से देखे जाते हैं। आप इसे यहाँ ऑनलाइन टेस्ट कर सकते हैं
उदाहरण के लिए, निम्नलिखित इनपुट स्ट्रिंग के साथ
BMI=(<<Weight>>/(<<Height>>*<<Height>>)) * 70
Hi there <<Weight>> was here
और निम्न चर मान
Weight, 42
Height, HEIGHT 51
निम्नलिखित आउटपुट
BMI=(42/(HEIGHT 51*HEIGHT 51)) * 70
Hi there 42 was here
यहाँ कोड है
static Pattern pattern = Pattern.compile("<<([a-z][a-z0-9]*)>>", Pattern.CASE_INSENSITIVE);
public static String replaceVarsWithValues(String message, Map<String,String> varValues) {
try {
StringBuffer newStr = new StringBuffer(message);
int lenDiff = 0;
Matcher m = pattern.matcher(message);
while (m.find()) {
String fullText = m.group(0);
String keyName = m.group(1);
String newValue = varValues.get(keyName)+"";
String replacementText = newValue;
newStr = newStr.replace(m.start() - lenDiff, m.end() - lenDiff, replacementText);
lenDiff += fullText.length() - replacementText.length();
}
return newStr.toString();
} catch (Exception e) {
return message;
}
}
public static void main(String args[]) throws Exception {
String testString = "BMI=(<<Weight>>/(<<Height>>*<<Height>>)) * 70\n\nHi there <<Weight>> was here";
HashMap<String,String> values = new HashMap<>();
values.put("Weight", "42");
values.put("Height", "HEIGHT 51");
System.out.println(replaceVarsWithValues(testString, values));
}
और यद्यपि अनुरोध नहीं किया गया है, आप अपनी एप्लिकेशन से संपत्तियों के साथ स्ट्रिंग में चर को बदलने के लिए एक समान दृष्टिकोण का उपयोग कर सकते हैं। हालांकि, यह पहले से ही किया जा रहा है:
private static Pattern patternMatchForProperties =
Pattern.compile("[$][{]([.a-z0-9_]*)[}]", Pattern.CASE_INSENSITIVE);
protected String replaceVarsWithProperties(String message) {
try {
StringBuffer newStr = new StringBuffer(message);
int lenDiff = 0;
Matcher m = patternMatchForProperties.matcher(message);
while (m.find()) {
String fullText = m.group(0);
String keyName = m.group(1);
String newValue = System.getProperty(keyName);
String replacementText = newValue;
newStr = newStr.replace(m.start() - lenDiff, m.end() - lenDiff, replacementText);
lenDiff += fullText.length() - replacementText.length();
}
return newStr.toString();
} catch (Exception e) {
return message;
}
}