Example usage for java.util.regex Matcher appendReplacement

List of usage examples for java.util.regex Matcher appendReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher appendReplacement.

Prototype

public Matcher appendReplacement(StringBuilder sb, String replacement) 

Source Link

Document

Implements a non-terminal append-and-replace step.

Usage

From source file:org.nuclos.common2.StringUtils.java

/**
 * Splits the given input sequence around matches of the given pattern but
 * also include the matches in the result.
 * All strings at odd indices are matches of the given pattern, all strings
 * at even indices are the splitted text fragments.
 *//*  w  ww.  j  a  va  2s .  co m*/
public static String[] splitWithMatches(Pattern pattern, int group, CharSequence input) {
    Matcher m = pattern.matcher(input);
    List<String> list = new ArrayList<String>();
    while (m.find()) {
        StringBuffer sb = new StringBuffer();
        m.appendReplacement(sb, "");
        list.add(sb.toString());
        list.add(m.group(group));
    }
    StringBuffer sb = new StringBuffer();
    m.appendTail(sb);
    list.add(sb.toString());
    return list.toArray(new String[list.size()]);
}

From source file:forge.game.spellability.AbilityManaPart.java

/**
 * <p>/*w  w w.  j  a  v  a  2 s  .c  om*/
 * applyManaReplacement.
 * </p>
 * @return a String
 */
public static String applyManaReplacement(final SpellAbility sa, final String original) {
    final HashMap<String, String> repMap = new HashMap<String, String>();
    final Player act = sa != null ? sa.getActivatingPlayer() : null;
    final String manaReplace = sa != null ? sa.getManaPart().getManaReplaceType() : "";
    if (manaReplace.isEmpty()) {
        if (act != null && act.getLandsPlayedThisTurn() > 0 && sa.hasParam("ReplaceIfLandPlayed")) {
            return sa.getParam("ReplaceIfLandPlayed");
        }
        return original;
    }
    if (manaReplace.startsWith("Any")) {
        // Replace any type and amount
        String replaced = manaReplace.split("->")[1];
        if (replaced.equals("Any")) {
            byte rs = MagicColor.GREEN;
            if (act != null) {
                rs = act.getController().chooseColor("Choose a color", sa, ColorSet.ALL_COLORS);
            }
            replaced = MagicColor.toShortString(rs);
        }
        return replaced;
    }
    final Pattern splitter = Pattern.compile("->");
    // Replace any type
    for (String part : manaReplace.split(" & ")) {
        final String[] v = splitter.split(part, 2);
        if (v[0].equals("Colorless")) {
            repMap.put("[0-9][0-9]?", v.length > 1 ? v[1].trim() : "");
        } else {
            repMap.put(v[0], v.length > 1 ? v[1].trim() : "");
        }
    }
    // Handle different replacement simultaneously
    Pattern pattern = Pattern.compile(StringUtils.join(repMap.keySet().iterator(), "|"));
    Matcher m = pattern.matcher(original);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        if (m.group().matches("[0-9][0-9]?")) {
            final String rep = StringUtils.repeat(repMap.get("[0-9][0-9]?") + " ", Integer.parseInt(m.group()))
                    .trim();
            m.appendReplacement(sb, rep);
        } else {
            m.appendReplacement(sb, repMap.get(m.group()));
        }
    }
    m.appendTail(sb);
    String replaced = sb.toString();
    while (replaced.contains("Any")) {
        byte rs = MagicColor.GREEN;
        if (act != null) {
            rs = act.getController().chooseColor("Choose a color", sa, ColorSet.ALL_COLORS);
        }
        replaced = replaced.replaceFirst("Any", MagicColor.toShortString(rs));
    }
    return replaced;
}

From source file:org.openpplsoft.sql.StmtLibrary.java

private static String processAndExpandWhereStr(final String rootAlias, final String whereStr) {

    String newWhereStr = whereStr;

    // Expand any %EffDtCheck meta-SQL
    final Matcher effDtCheckMatcher = effDtCheckPattern.matcher(newWhereStr);
    while (effDtCheckMatcher.find()) {

        final String effDtCheckRecord = effDtCheckMatcher.group(1);
        // Do not use group 2 (contains whitespace preceding the optional subquery alias)
        String effDtSubqueryAlias = effDtCheckMatcher.group(3);
        final String effDtRootAlias = effDtCheckMatcher.group(4);
        String effDtBound = effDtCheckMatcher.group(5);

        if (!rootAlias.equals(effDtRootAlias)) {
            throw new OPSVMachRuntimeException(
                    "While preparing fill query, " + "found %EffDtCheck that has a root alias ("
                            + effDtRootAlias + ") different than expected (" + rootAlias + ").");
        }/*from w  ww  .ja va  2  s. c  om*/

        // If subquery alias is not specified, use name of record being checked.
        if (effDtSubqueryAlias == null) {
            effDtSubqueryAlias = effDtCheckRecord;
        }

        StringBuilder effDtSubqueryBuilder = new StringBuilder("SELECT MAX(EFFDT) FROM ")
                .append(effDtCheckRecord).append(' ').append(effDtSubqueryAlias).append(" WHERE");

        final Record effDtRecord = DefnCache.getRecord(effDtCheckRecord);
        for (final Map.Entry<String, RecordField> cursor : effDtRecord.getFieldTable().entrySet()) {
            final RecordField rf = cursor.getValue();
            if (rf.isKey() && !rf.getFldName().equals("EFFDT")) {
                effDtSubqueryBuilder.append(' ').append(effDtSubqueryAlias).append('.').append(rf.getFldName())
                        .append('=').append(effDtRootAlias).append('.').append(rf.getFldName()).append(" AND");
            }
        }

        // If the effDtBound is not a meta-sql construct, it will not
        // be wrapped with TO_DATE later in this function, so wrap it now.
        if (effDtBound.length() == 0 || effDtBound.charAt(0) != '%') {
            effDtBound = "TO_DATE(" + effDtBound + ",'YYYY-MM-DD')";
        }

        effDtSubqueryBuilder.append(' ').append(effDtSubqueryAlias).append(".EFFDT<=").append(effDtBound);

        newWhereStr = effDtCheckMatcher
                .replaceAll(effDtRootAlias + ".EFFDT=(" + effDtSubqueryBuilder.toString() + ")");
    }

    // Replace occurrences of %DATEIN/DateIn with TO_DATE(*,'YYYY-MM-DD')
    final Matcher dateInMatcher = dateInPattern.matcher(newWhereStr);
    final StringBuffer dateInSb = new StringBuffer();
    while (dateInMatcher.find()) {
        dateInMatcher.appendReplacement(dateInSb, "TO_DATE(" + dateInMatcher.group(2) + ",'YYYY-MM-DD')");
    }
    dateInMatcher.appendTail(dateInSb);
    newWhereStr = dateInSb.toString();

    // Replace occurrences of %CurrentDateIn
    final Matcher currDateInMatcher = currDateInPattern.matcher(newWhereStr);
    newWhereStr = currDateInMatcher.replaceAll("TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')");

    return newWhereStr;
}

From source file:com.krawler.common.util.BaseStringUtil.java

public static String serverHTMLStripper(String stripTags)
        throws IllegalStateException, IndexOutOfBoundsException {
    Pattern p = Pattern.compile("<[^>]*>");
    Matcher m = p.matcher(stripTags);
    StringBuffer sb = new StringBuffer();
    if (!isNullOrEmpty(stripTags)) {
        while (m.find()) {
            m.appendReplacement(sb, "");
        }/*from  w ww  .  ja  v  a 2 s  .  c  om*/
        m.appendTail(sb);
        stripTags = sb.toString();
    }
    return stripTags.trim();
}

From source file:com.yahoo.glimmer.web.QueryController.java

/**
 * Replaces '{' + resourceString + '}' with '@' + resourceId.
 * //from   w  ww.ja  va 2 s .c  om
 * @param index
 * @param query
 * @return re-written query.
 * @throws IllegalArgumentException when a resource that is not in the data set is found in the given query.
 */
public static String encodeResources(RDFIndex index, String query) {
    Matcher resourceMatcher = RESOURCE_PATTERN.matcher(query);
    StringBuffer sb = new StringBuffer();
    while (resourceMatcher.find()) {
        String resource = resourceMatcher.group(0);
        // Remove { and }
        resource = resource.substring(1, resource.length() - 1);

        // TODO. Objects that are Resources aren't converted to lower case during indexing but predicates are!
        // (in PredicatePrefixTupleFilter)  Needs to be consistent.
        String resourceId = index.lookupIdByResourceId(resource);
        if (resourceId == null) {
            resourceId = index.lookupIdByResourceId(resource.toLowerCase());
            if (resourceId == null) {
                throw new IllegalArgumentException("The resource " + resource + " isn't in the data set.");
            }
        }
        resourceMatcher.appendReplacement(sb, resourceId);
    }
    resourceMatcher.appendTail(sb);

    return sb.toString();
}

From source file:autocorrelator.apps.SDFGroovy.java

/**
 * Parse groovyStrng for input and output variables marked by $&lt;&gt;
 *    and create {@link Script} object.//from   ww  w .  j  a v  a 2  s  .c o  m
 * @param groovyStrg string containing groovy script
 * @param initArgs arguments to be passed to init() method if exists
 * @param outFields Set to be filled with output variable names
 * @return pre compiled groovy script
 */
private static Script getGroovyScript(String groovyStrg, Set<String> inFields, Set<String> outFields) {
    StringBuffer sb = new StringBuffer(groovyStrg.length());
    Matcher varMatch = VARIABLEPat.matcher(groovyStrg);

    // Identify in and out variables in script by looking for
    // $(>|<>)?[a-zA-Z_][a-zA-Z_0-9]*
    while (varMatch.find()) {
        String var = varMatch.group();

        /*Remove the prefix $(>|<>)? to get correct variable names.*/
        String varName = var.replaceAll(TASK_VAR_FLAG, "");

        if (INVariablePat.matcher(var).find()) //input
            inFields.add(varName);
        else if (OUTVariablePat.matcher(var).find()) //output
            outFields.add(varName);
        else //input & output
        {
            inFields.add(varName);
            outFields.add(varName);
        }
        varMatch.appendReplacement(sb, varName);
    }
    varMatch.appendTail(sb);

    groovyStrg = "import static autocorrelator.apps.SDFGroovyHelper.*;\n " + sb.toString();
    GroovyShell shell = new GroovyShell();
    Script script;
    try {
        script = shell.parse(groovyStrg);
    } catch (CompilationFailedException e) {
        System.err.println(groovyStrg);
        throw e;
    }
    return script;
}

From source file:com.krawler.common.util.BaseStringUtil.java

private static String replaceAll(String text, Pattern pattern, String replace) {
    Matcher m = pattern.matcher(text);
    StringBuffer sb = null;//  w w w  .  j a  va2  s . c om
    while (m.find()) {
        if (sb == null)
            sb = new StringBuffer();
        m.appendReplacement(sb, replace);
    }
    if (sb != null)
        m.appendTail(sb);
    return sb == null ? text : sb.toString();
}

From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java

private static String changeImageUrls(String contextPath, String cssSourceCode, String cssPath) {
    Matcher matcher = CSS_URL_PATTERN.matcher(cssSourceCode);
    StringBuffer sb = new StringBuffer();

    Path basePath = Paths.get(contextPath + cssPath);

    while (matcher.find()) {
        String url = matcher.group(2);
        url = url.trim();//from www .  j  a  v  a 2 s  .c  o  m
        if (url.equals("#default#VML") || url.startsWith("data:")) {
            continue;
        }
        Path pa = basePath.resolveSibling(url).normalize();
        matcher.appendReplacement(sb, "$1" + pa.toString().replace("\\", "/") + "$3$4");
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:net.triptech.metahive.CalculationParser.java

/**
 * Builds the calculation./*from w  w w .jav a 2  s  . c  o m*/
 *
 * @param calculation the calculation
 * @param values the values
 * @return the string
 */
public static String buildCalculation(String calculation, Map<Long, Double> values) {

    String parsedCalculation = "";

    logger.debug("Calculation: " + calculation);
    logger.debug("Values: " + values);

    if (StringUtils.isNotBlank(calculation) && values != null) {
        try {
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(calculation);
            StringBuffer sb = new StringBuffer();
            logger.debug("Regular expression: " + regEx);
            while (m.find()) {
                logger.info("Variable instance found: " + m.group());
                try {
                    String text = m.group();
                    Long id = Long.parseLong(StringUtils.substring(text, 1));
                    logger.info("Variable id: " + id);

                    if (values.containsKey(id)) {
                        logger.debug("Contains variable " + id);
                        double value = values.get(id);
                        logger.debug("Value: " + value);
                        text = String.valueOf(value);
                    }
                    logger.debug("Replacement text: " + text);
                    m.appendReplacement(sb, Matcher.quoteReplacement(text));

                } catch (NumberFormatException nfe) {
                    logger.error("Error parsing variable id");
                }
            }
            m.appendTail(sb);

            parsedCalculation = sb.toString();
            logger.info("Parsed calculation: " + parsedCalculation);

        } catch (PatternSyntaxException pe) {
            logger.error("Regex syntax error ('" + pe.getPattern() + "') " + pe.getMessage());
        }
    }
    return parsedCalculation;
}

From source file:com.yukthi.utils.MessageFormatter.java

/**
 * Replaces the args values in "message" using patterns mentioned below and same will be returned. 
 * //  w  w w  .  j ava 2  s  . com
 * {} will match with the current index argument. If index is greater than provided values then &lt;undefined&gt; string will be used.
 * {&lt;idx&gt;} can be used to refer to argument at particular index. Helpful in building messages which uses same argument multiple times.
 * 
 * @param message Message string with expressions
 * @param args Values for expression
 * @return Formatted string
 */
public static String format(String message, Object... args) {
    //when message is null, return null
    if (message == null) {
        return null;
    }

    //when args is null, assume empty values
    if (args == null) {
        args = new Object[0];
    }

    Matcher matcher = PARAM_PATTERN.matcher(message);
    StringBuffer buffer = new StringBuffer();

    int loopIndex = 0;
    int argIndex = 0;
    Object arg = null;

    //loop through pattern matches
    while (matcher.find()) {
        //if index is mentioned in pattern
        if (StringUtils.isNotBlank(matcher.group(1))) {
            argIndex = Integer.parseInt(matcher.group(1));
        }
        //if index is not specified, use current loop index
        else {
            argIndex = loopIndex;
        }

        //if the index is within provided arguments length
        if (argIndex < args.length) {
            arg = args[argIndex];
        }
        //if the index is greater than available values
        else {
            arg = UNDEFINED;
        }

        //if argument value is null
        if (arg == null) {
            arg = "null";
        }

        matcher.appendReplacement(buffer, arg.toString());
        loopIndex++;
    }

    matcher.appendTail(buffer);
    return buffer.toString();
}