Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save muhdkhokhar/bbc645bb9e2a7c37090c6996868b14c6 to your computer and use it in GitHub Desktop.
Save muhdkhokhar/bbc645bb9e2a7c37090c6996868b14c6 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PlaceholderReplacer {
public static void main(String[] args) {
String input = "abc %current_uk_time% test %another_one%";
// Create a map with placeholder values
Map<String, String> placeholderValues = new HashMap<>();
placeholderValues.put("current_uk_time", "10:30 AM");
placeholderValues.put("another_one", "Hello, World!");
// Replace placeholders in the input string
String result = replacePlaceholders(input, placeholderValues);
System.out.println(result); // Output: abc 10:30 AM test Hello, World!
}
public static String replacePlaceholders(String input, Map<String, String> placeholderValues) {
// Pattern to match placeholders in the format %placeholder_name%
Pattern pattern = Pattern.compile("%(.*?)%");
Matcher matcher = pattern.matcher(input);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
String placeholder = matcher.group(1);
String replacement = placeholderValues.getOrDefault(placeholder, matcher.group(0));
matcher.appendReplacement(result, replacement);
}
matcher.appendTail(result);
return result.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment