001package gudusoft.gsqlparser.util;
002
003import java.util.Map;
004import java.util.regex.Matcher;
005import java.util.regex.Pattern;
006
007public class VariableSubstitutor {
008    // Pattern to match ${variableName} format
009    private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\{([^}]+)}");
010
011    public static String substituteVariables(String input, Map<String, String> variables) {
012        if (input == null || variables == null) {
013            return input;
014        }
015
016        StringBuffer result = new StringBuffer();
017        Matcher matcher = VARIABLE_PATTERN.matcher(input);
018
019        while (matcher.find()) {
020            String variableName = matcher.group(1);
021            String replacement = variables.get(variableName);
022            
023            // If variable not found in map, leave the original ${variableName}
024            if (replacement == null) {
025                replacement = "${" + variableName + "}";
026            }
027            
028            // Quote the replacement string to handle special regex characters
029            matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
030        }
031        matcher.appendTail(result);
032
033        return result.toString();
034    }
035}