Search in sources :

Example 1 with UnknownExpressionException

use of com.devonfw.cobigen.api.exception.UnknownExpressionException in project cobigen by devonfw.

the class Variables method applyStringModifier.

/**
 * Applies the given {@link String} modifier defined by ?modifier behind the variable reference
 *
 * @param modifierName name of the {@link String} modifier to be applied
 * @param string {@link String} the modifier should be applied on
 * @return the modified {@link String}
 * @throws UnknownExpressionException if there is an unknown variable modifier
 */
private String applyStringModifier(String modifierName, String string) throws UnknownExpressionException {
    // simple operators
    if (modifierName.equals("cap_first")) {
        return StringUtil.capFirst(string);
    } else if (modifierName.equals("uncap_first")) {
        return StringUtil.uncapFirst(string);
    } else if (modifierName.equals("lower_case")) {
        return string.toLowerCase();
    } else if (modifierName.equals("upper_case")) {
        return string.toUpperCase();
    }
    String parameterRegex = "\\s*'([^']*)'\\s*";
    // ?replace(String regex, String replacement)
    Pattern p = Pattern.compile("replace\\(" + parameterRegex + "," + parameterRegex + "\\)");
    Matcher m = p.matcher(modifierName);
    if (m.matches()) {
        return string.replaceAll(m.group(1), m.group(2));
    }
    // ?removeSuffix(String suffix)
    p = Pattern.compile("removeSuffix\\(" + parameterRegex + "\\)");
    m = p.matcher(modifierName);
    if (m.matches() && string.endsWith(m.group(1))) {
        return string.substring(0, string.length() - m.group(1).length());
    }
    // ?removePrefix(String prefix)
    p = Pattern.compile("removePrefix\\(" + parameterRegex + "\\)");
    m = p.matcher(modifierName);
    if (m.matches() && string.startsWith(m.group(1))) {
        return string.substring(m.group(1).length(), string.length());
    }
    throw new UnknownExpressionException("?" + modifierName);
}
Also used : Pattern(java.util.regex.Pattern) UnknownExpressionException(com.devonfw.cobigen.api.exception.UnknownExpressionException) Matcher(java.util.regex.Matcher)

Aggregations

UnknownExpressionException (com.devonfw.cobigen.api.exception.UnknownExpressionException)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1