All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.qoomon.gitversioning.StringUtil Maven / Gradle / Ivy

package me.qoomon.gitversioning;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class StringUtil {

    public static String substituteText(String text, Map substitutionMap) {
        String result = text;

        final Pattern placeholderPattern = Pattern.compile("\\$\\{(.+?)}");
        final Matcher placeholderMatcher = placeholderPattern.matcher(text);
        while (placeholderMatcher.find()) {
            String substitutionKey = placeholderMatcher.group(1);
            String substitutionValue = substitutionMap.get(substitutionKey);
            if(substitutionValue != null) {
                result = result.replaceAll("\\$\\{" + substitutionKey + "}", substitutionValue);
            }
        }

        return result;
    }

    /**
     * @param regex pattern
     * @param text  to parse
     * @return a map of group-index and group-name to matching value
     */
    public static Map valueGroupMap(String regex, String text) {
        Map result = new HashMap<>();
        Pattern groupPattern = Pattern.compile(regex);
        Matcher groupMatcher = groupPattern.matcher(text);
        if (groupMatcher.find()) {
            // add group index to value entries
            for (int i = 0; i <= groupMatcher.groupCount(); i++) {
                result.put(String.valueOf(i), groupMatcher.group(i));
            }

            patternGroupNames(groupPattern).forEach(groupName -> result.put(groupName, groupMatcher.group(groupName)));
        }
        return result;
    }

    private static Set patternGroupNames(Pattern groupPattern) {
        Set groupNames = new HashSet<>();
        Pattern groupNamePattern = Pattern.compile("\\(\\?<(?[a-zA-Z][a-zA-Z0-9]*)>");
        Matcher groupNameMatcher = groupNamePattern.matcher(groupPattern.toString());

        // add group name to value Entries
        while (groupNameMatcher.find()) {
            String groupName = groupNameMatcher.group("name");
            groupNames.add(groupName);
        }
        return groupNames;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy