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.ourbeehive.mbp.util.StringHelper.java

/**
 * Remove non-eligible characters in phase. Please note that the order of regular expressions in this method could not be changed.
 * //w  w w . ja va  2  s  .c  o m
 * @param phase
 * @return
 */
public static String removeNonEligibleChar(String phase) {

    String result = phase;

    // Replace invalid characters with " ".
    Pattern pattern = Pattern.compile("[-]|['\"_,%?./&():]");
    Matcher matcher = pattern.matcher(result);
    result = matcher.replaceAll(" ");

    // Add "_" before number if number is the first character.
    pattern = Pattern.compile("^\\d");
    matcher = pattern.matcher(result);
    if (matcher.find()) {
        result = "_" + result;
    }

    // Replace "#" followed by number.
    pattern = Pattern.compile("#[ ]*[0-9]");
    Pattern subPat = Pattern.compile("#[ ]*");
    matcher = pattern.matcher(result);
    String currMat = null;
    Matcher subMat = null;
    StringBuffer sb = new StringBuffer();
    int start, end = 0;
    while (matcher.find()) {
        start = matcher.start();
        end = matcher.end();
        currMat = result.substring(start, end);
        subMat = subPat.matcher(currMat);
        matcher.appendReplacement(sb, subMat.replaceAll(""));
    }
    matcher.appendTail(sb);

    // Replace "#" followed by character with " Number ".
    pattern = Pattern.compile("#");
    matcher = pattern.matcher(result);
    result = matcher.replaceAll(" Number ");

    // Replace "Y/N" with " ".
    pattern = Pattern.compile("Y/N", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(result);
    result = matcher.replaceAll(" ");

    // Replace "A/C" with "Account".
    pattern = Pattern.compile("A/C", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(result);
    result = matcher.replaceAll("Acount");

    // Replace "DDMMYYYY" and "DDMMYY" with " ".
    pattern = Pattern.compile("DDMMY*", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(result);
    result = matcher.replaceAll(" ");

    // Replace "HHMMSS" with " ".
    pattern = Pattern.compile("HHMMSS", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(result);
    result = matcher.replaceAll(" ");

    // Remove extra white space.
    pattern = Pattern.compile("[ ]+");
    matcher = pattern.matcher(result);
    result = matcher.replaceAll(" ");

    return result.trim().replace("*", " ");

}

From source file:io.scigraph.internal.CypherUtil.java

public String resolveRelationships(String cypher) {
    Matcher m = ENTAILMENT_PATTERN.matcher(cypher);
    StringBuffer buffer = new StringBuffer();
    while (m.find()) {
        String varName = m.group(1);
        String types = m.group(2);
        String modifiers = m.group(3);
        Collection<String> resolvedTypes = resolveTypes(types, modifiers.contains("!"));
        modifiers = modifiers.replaceAll("!", "");
        String typeString = resolvedTypes.isEmpty() ? "" : ":`" + on("`|`").join(resolvedTypes) + "`";
        m.appendReplacement(buffer, "[" + varName + typeString + modifiers + "]");
    }/*w w w .ja  va  2 s. c o  m*/
    m.appendTail(buffer);
    return buffer.toString();
}

From source file:mergedoc.core.JavaBuffer.java

/**
 * ?????????//from  ww  w  . j  av a2  s .  co  m
 * @return ?????????? null
 */
public Signature getSignature() {
    int commentEndPos = commentMatcher.end();
    String commentEndToEOF = source.substring(commentEndPos, source.length());
    // ??????????
    Matcher matcher = PatternCache.getPattern("(?s)/\\*(.*?)\\*/").matcher(commentEndToEOF);
    StringBuffer sb = new StringBuffer(commentEndToEOF.length());
    while (matcher.find()) {
        matcher.appendReplacement(sb, "/*");
        char[] cs = matcher.group(1).toCharArray();
        for (char c : cs) {
            switch (c) {
            case '*':
            case '\n':
                sb.append(c);
                break;
            default:
                sb.append(' ');
                break;
            }
        }
        sb.append("*/");
    }
    matcher.appendTail(sb);
    commentEndToEOF = sb.toString();

    // ???????????
    commentEndToEOF = FastStringUtils.replaceFirst(commentEndToEOF, "(?s)^(\\s*@[\\w]+\\s*\\(.*?\\))*\\s*", "");

    Pattern sigPattern = PatternCache.getPattern("(?s)(.+?)(throws|\\{|\\=|;|,\\s*/\\*|\\})");
    Matcher sigMatcher = sigPattern.matcher(commentEndToEOF);

    if (sigMatcher.find()) {

        // ?????
        ClassBlock classBlock = classStack.peek();
        while (commentEndPos > classBlock.end && classStack.size() > 1) {
            classStack.pop();
            classBlock = classStack.peek();
        }

        // ???Javadoc ?????
        // ?????????
        String sigStr = sigMatcher.group(1);
        sigStr = FastStringUtils.replaceFirst(sigStr, "(?s)/\\*[^\\*].*?\\*/\\s*", "");
        if (classKind.equals("@interface")) {
            sigStr = sigStr.replace("()", "");
        }
        Signature sig = new Signature(classBlock.name, sigStr);

        // ????
        if (sig.isDeclareInnerClass()) {
            String name = sig.getClassName();
            int end = searchEndOfInner(commentEndToEOF, name);
            classBlock = new ClassBlock(name, end);
            classStack.push(classBlock);
        }

        return sig;
    }

    log.warn("Javadoc ?????????????\n"
            + commentEndToEOF);
    return null;
}

From source file:org.cesecore.certificates.ocsp.logging.PatternLogger.java

/**
 * /* w w w . j a  va  2 s. c o  m*/
 * @return output to be logged
 */
private String interpolate() {
    final StringBuffer sb = new StringBuffer(this.orderString.length());
    final Matcher matcher = getMatcher();
    matcher.reset();
    while (matcher.find()) {
        // when the pattern is ${identifier}, group 0 is 'identifier'
        final String key = matcher.group(1);
        final String value = this.valuepairs.get(key);

        // if the pattern does exists, replace it by its value
        // otherwise keep the pattern ( it is group(0) )
        if (value != null) {
            matcher.appendReplacement(sb, value);
        } else {
            // I'm doing this to avoid the backreference problem as there will be a $
            // if I replace directly with the group 0 (which is also a pattern)
            matcher.appendReplacement(sb, "");
            final String unknown = matcher.group(0);
            sb.append(unknown);
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.dd4t.core.filters.impl.DefaultLinkResolverFilter.java

protected void resolveXhtmlField(XhtmlField xhtmlField) {

    StopWatch stopWatch = null;//w ww . j  av  a2s. c o  m
    if (logger.isDebugEnabled()) {
        stopWatch = new StopWatch();
        stopWatch.start();
    }

    List<Object> xhtmlValues = xhtmlField.getValues();
    List<String> newValues = new ArrayList<String>();

    if (useXslt) {
        // find all component links and try to resolve them
        for (Object xhtmlValue : xhtmlValues) {
            String result = xslTransformer.transformSourceFromFilesource(
                    "<ddtmproot>" + (String) xhtmlValue + "</ddtmproot>", "/resolveXhtmlWithLinks.xslt",
                    params);
            newValues.add(XSLTPattern.matcher(result).replaceAll(""));
        }
    } else {
        // find all component links and try to resolve them
        for (Object xhtmlValue : xhtmlValues) {

            Matcher m = RegExpPattern.matcher((String) xhtmlValue);

            StringBuffer sb = new StringBuffer();
            String resolvedLink = null;
            while (m.find()) {
                resolvedLink = getLinkResolver().resolve(m.group(1));
                // if not possible to resolve the link do nothing
                if (resolvedLink != null) {
                    m.appendReplacement(sb, "href=\"" + resolvedLink + "\"");
                }
            }
            m.appendTail(sb);
            newValues.add(sb.toString());
        }

    }

    xhtmlField.setTextValues(newValues);

    if (logger.isDebugEnabled()) {
        stopWatch.stop();
        logger.debug("Parsed rich text field '" + xhtmlField.getName() + "' in "
                + stopWatch.getTotalTimeMillis() + " ms.");
    }
}

From source file:org.pentaho.platform.plugin.services.metadata.SessionAwareRowLevelSecurityHelper.java

@Override
protected String expandFunctions(String formula, String user, List<String> roles) {
    formula = super.expandFunctions(formula, user, roles);

    // "expand" any SESSION('var')

    IPentahoSession session = PentahoSessionHolder.getSession();

    Pattern p = Pattern.compile("SESSION\\(\"(.*?)\"\\)"); //$NON-NLS-1$
    Matcher m = p.matcher(formula);
    StringBuffer sb = new StringBuffer(formula.length());
    while (m.find()) {
        String text = m.group(1);
        String value = null;//from  w  ww  . java 2  s .  c  o m
        if (session.getAttribute(text) != null) {
            value = session.getAttribute(text).toString();
        } else {
            logger.warn(Messages.getInstance()
                    .getString("SessionAwareRowLevelSecurityHelper.WARN_0001_NULL_ATTRIBUTE", text, user)); //$NON-NLS-1$
            return "FALSE()"; //$NON-NLS-1$
        }
        // escape string if necessary (double quote quotes)
        m.appendReplacement(sb, Matcher.quoteReplacement(value.replaceAll("\"", "\"\""))); //$NON-NLS-1$ //$NON-NLS-2$
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:models.GroupSerializer.java

protected String parseReferencesInComment(Group group) {
    CarbonOntology ontology = CarbonOntology.getInstance();
    Pattern p = Pattern.compile("\\{[^}]*\\}");
    Matcher m = p.matcher(group.getComment());
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String refId = m.group().substring(1, m.group().length() - 1);
        try {//from w  ww.j  a  v  a2  s.  co  m
            Reference ref = ontology.getReference(refId);
            if (!group.getReferences().contains(ref)) {
                log.warn("The reference " + ref.getId() + " in the group " + group.getId()
                        + "comment is not in the group reference list");
            }
            m.appendReplacement(sb, "[" + ref.getShortName() + "]");
        } catch (NotFoundException e) {
            log.warn("Unable to replace a reference in the group " + group.getId() + " comment: "
                    + e.getMessage());
            m.appendReplacement(sb, "[" + refId + "]");
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.gewara.util.XSSFilter.java

protected String checkTags(String s) {
    Pattern p = Pattern.compile("<(.*?)>", Pattern.DOTALL);
    Matcher m = p.matcher(s);

    StringBuffer buf = new StringBuffer();
    while (m.find()) {
        String replaceStr = m.group(1);
        replaceStr = processTag(replaceStr);
        m.appendReplacement(buf, replaceStr);
    }/*from www .j  a  v  a2s.co m*/
    m.appendTail(buf);

    s = buf.toString();

    // these get tallied in processTag
    // (remember to reset before subsequent calls to filter method)
    for (String key : vTagCounts.keySet()) {
        for (int ii = 0; ii < vTagCounts.get(key); ii++) {
            s += "</" + key + ">";
        }
    }

    return s;
}

From source file:org.kuali.rice.kew.impl.document.search.DocumentSearchCriteriaBoLookupableHelperService.java

protected static String replaceCurrentUserToken(String value, Person person) {
    Matcher matcher = CURRENT_USER_PATTERN.matcher(value);
    boolean matched = false;
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matched = true;/*from ww w  . jav  a2 s .c  o m*/
        String idType = "principalName";
        if (matcher.groupCount() > 0) {
            String group = matcher.group(1);
            if (group != null) {
                idType = group.substring(1); // discard period after CURRENT_USER
            }
        }
        String idValue = UserUtils.getIdValue(idType, person);
        if (!StringUtils.isBlank(idValue)) {
            value = idValue;
        } else {
            value = matcher.group();
        }
        matcher.appendReplacement(sb, value);

    }
    matcher.appendTail(sb);
    return matched ? sb.toString() : null;
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

private String escapeNonXMLEntityRefs(final String xml) {
    final Matcher m = Pattern.compile("&([^\\s;]+;)").matcher(xml);

    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String value = m.group();
        if (!XML_ENTITIES.contains(value)) {
            value = "&amp;" + m.group(1);
        }//w ww  .  j  a  v  a 2 s  .  c o  m

        m.appendReplacement(sb, value);
    }

    m.appendTail(sb);

    return sb.toString();
}