Java parses {variable names and text content replacement operations

51CTO2022-05-14 19:33:31



/**
* Get the list of variable names in the text according to the regular expression
* @param pattern
* @param content
* @return
*/
public static List<String> getParams(String pattern, String content) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);

List<String> result = new ArrayList<String>();
while (m.find()) {
result.add(m.group(1));
}
return result;
}

/**
* Replace the variables in the text with the actual data according to the regular expression
* @param pattern
* @param content
* @param data
* @return
*/
public static String parse(String pattern, String content, Map<String, String> data) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);

StringBuffer sb = new StringBuffer();
while (m.find()) {
String key = m.group(1);
String value = data.get(key);
m.appendReplacement(sb, value == null ? "" : value);
}
m.appendTail(sb);
return sb.toString();
}

public static void main(String[] args) {
String content = " Congratulations {{ full name }} Successful registration , Please show your registration number {[code]} Go to the scene and take part in activities ";
String reg = "\\{\\{(.+?)\\}\\}";
List<String> params = getParams(reg, content);
System.out.println(params);

Map<String, String> data = new HashMap<String, String>();
data.put(" full name ", " Zhang Sanfeng ");
data.put("code", "930118");
String text = parse(reg, content, data);
System.out.println(text);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.






thank
Similar articles