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:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

public String replaceProperties(String string) {
    if (string == null)
        return null;

    Matcher m = mavenPropertyPattern.matcher(string);

    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        String propertyName = m.group(1);
        String propertyValue = getPropertyValue(propertyName);
        if (propertyValue != null) {
            m.appendReplacement(sb, Matcher.quoteReplacement(propertyValue));
        }// w  w w  .j a v  a 2 s .c  o m
    }
    m.appendTail(sb);
    string = sb.toString();

    return string;
}

From source file:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java

protected void importMarkupStyle1(Pattern titlePattern, Markup titlePrefix, Reader markupText,
        MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;//from  ww w  .  j av a  2  s  . com
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = titleMatcher.group(1).length() - 1;
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format(
                            "Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)",
                            levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(
                            String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0",
                                    levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String.format("%s %s",
                            StringUtils.repeat(titlePrefix.toString(), 1 + titleLevel + levelOffset), title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}

From source file:gtu._work.etc.EnglishTester.java

String formatChangeLine(String question, String answer) {
    answer = answer.replaceAll("\\[.*\\]", "");
    answer = answer.replaceAll("-", "");

    Pattern ptn = Pattern.compile(question, Pattern.CASE_INSENSITIVE);
    Matcher matcher = ptn.matcher(answer);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, "");
    }//from   w w w .  java2s .co m
    matcher.appendTail(sb);
    return "<html>" + sb.toString() + "</html>";
}

From source file:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java

protected void importMarkupStyle2(Pattern titlePattern, String titleFormat, boolean startFrom0,
        Reader markupText, MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;/*w  w  w  .  j  a  v  a  2s . c o  m*/
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = Integer.valueOf(titleMatcher.group(1)) - (startFrom0 ? 0 : 1);
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format(
                            "Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)",
                            levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(
                            String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0",
                                    levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String
                            .format(titleFormat, (startFrom0 ? 0 : 1) + titleLevel + levelOffset, title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}

From source file:mergedoc.core.APIDocument.java

/**
 * HTML ? A  Javadoc ? link ????/*  w w w . j  av  a 2s  . c o  m*/
 * <p>
 * ?? Javadoc ?? Comment ?????????
 * ?????Javadoc ? see ?????????
 * ??????
 *
 * @param className ??
 * @param html HTML ? A ?
 * @return Javadoc link 
 */
private String formatLinkTag(String className, String html) {

    StringBuffer sb = new StringBuffer();
    Matcher linkMatcher = linkClassPattern.matcher(html);

    while (linkMatcher.find()) {

        String url = linkMatcher.group(1).trim();
        String label = linkMatcher.group(2).trim();
        String ref = formatClassName(className, url);
        Pattern methodRefPat = PatternCache.getPattern("-(.*)-$");
        Matcher methodRefMat = methodRefPat.matcher(ref);
        if (methodRefMat.find()) {
            ref = FastStringUtils.replaceAll(ref, "-(.*)-$", "($1)"); // for Java8
            ref = FastStringUtils.replace(ref, "-", ","); // for Java8
            ref = FastStringUtils.replace(ref, ":A", "[]"); // for Java8
        }

        StringBuilder link = new StringBuilder();
        link.append("{@link ");
        link.append(ref);
        if (label.length() > 0) {

            ref = ref.replace('#', '.');
            if (!ref.endsWith(label)) {
                link.append(" ");
                link.append(label);
            }
        }
        link.append("}");

        linkMatcher.appendReplacement(sb, link.toString());
    }
    linkMatcher.appendTail(sb);
    html = sb.toString();

    return html;
}

From source file:org.opennms.ng.dao.support.DefaultResourceDao.java

/**
 * Fetch a specific resource by string ID.
 * @return Resource or null if resource cannot be found.
 * @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
 * @throws org.springframework.orm.ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
 *///w ww  .java2  s  .  c om
@Override
public OnmsResource getResourceById(String id) {
    OnmsResource resource = null;

    Pattern p = Pattern.compile("([^\\[]+)\\[([^\\]]*)\\](?:\\.|$)");
    Matcher m = p.matcher(id);
    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        String resourceTypeName = DefaultResourceDao.decode(m.group(1));
        String resourceName = DefaultResourceDao.decode(m.group(2));

        try {
            if (resource == null) {
                resource = getTopLevelResource(resourceTypeName, resourceName);
            } else {
                resource = getChildResource(resource, resourceTypeName, resourceName);
            }
        } catch (Throwable e) {
            LOG.warn("Could not get resource for resource ID \"{}\"", id, e);
            return null;
        }

        m.appendReplacement(sb, "");
    }

    m.appendTail(sb);

    if (sb.length() > 0) {
        LOG.warn("resource ID '{}' does not match pattern '{}' at '{}'", id, p.toString(), sb);
        return null;
    } else {
        return resource;
    }
}

From source file:mergedoc.core.Comment.java

/**
 * JDK1.5  API ???? pre HTML ??/*  www .  j  ava  2 s . co  m*/
 * ???????????Java ?????
 * ????pre ????????????? API ?
 * ???
 */
private void replacePreBody() {

    // pre ??????????
    if (!docBody.contains("<pre>")) {
        return;
    }

    // Java ? pre ??
    LinkedList<String> pres = null;
    String commentBody = FastStringUtils.replaceAll(srcBody, "(?m)^\\s*\\*( |)", "");
    Pattern pat = PatternCache.getPattern("(?s)(<pre>\n)(.+?)(\n</pre>)");
    Matcher mat = pat.matcher(commentBody);
    while (mat.find()) {
        if (pres == null) {
            pres = new LinkedList<String>();
        }
        pres.add(mat.group(2));
    }
    if (pres == null) {
        return;
    }

    // API ? pre ?? Java ???
    Matcher descMatcher = pat.matcher(docBody);
    StringBuffer sb = new StringBuffer();
    while (descMatcher.find()) {

        // pre ??????????
        if (pres.size() == 0) {
            return;
        }
        String value = FastStringUtils.quoteReplacement(pres.removeFirst());
        descMatcher.appendReplacement(sb, "$1" + value + "$3");
    }
    descMatcher.appendTail(sb);

    // pre ????????
    if (pres.size() == 0) {
        docBody = sb.toString();
    }
}

From source file:org.nuxeo.common.utils.TextTemplate.java

/**
 * That method is not recursive. It processes the given text only once.
 *
 * @param props CryptoProperties containing the variable values
 * @param text Text to process//from w ww. j a v  a2s  .  co  m
 * @return the processed text
 * @since 7.4
 */
protected String processString(CryptoProperties props, String text) {
    Matcher m = PATTERN.matcher(text);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        // newVarsValue == ${[#]embeddedVar[:=default]}
        String embeddedVar = m.group(PATTERN_GROUP_VAR);
        String value = props.getProperty(embeddedVar, keepEncryptedAsVar);
        if (value == null) {
            value = m.group(PATTERN_GROUP_DEFAULT);
        }
        if (value != null) {
            if (trim) {
                value = value.trim();
            }
            if (Crypto.isEncrypted(value)) {
                if (keepEncryptedAsVar && m.group(PATTERN_GROUP_DECRYPT) == null) {
                    value = "${" + embeddedVar + "}";
                } else {
                    value = new String(vars.getCrypto().decrypt(value));
                }
            }

            // Allow use of backslash and dollars characters
            value = Matcher.quoteReplacement(value);
            m.appendReplacement(sb, value);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:org.opennms.ng.dao.support.DefaultResourceDao.java

/**
 * Fetch a specific list of resources by string ID.
 * @return Resources or null if resources cannot be found.
 * @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
 * @throws org.springframework.orm.ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
 *//*from   w w w  . j  a va  2  s . c om*/
@Override
public List<OnmsResource> getResourceListById(String id)
        throws IllegalArgumentException, ObjectRetrievalFailureException {
    OnmsResource topLevelResource = null;

    Pattern p = Pattern.compile("([^\\[]+)\\[([^\\]]*)\\](?:\\.|$)");
    Matcher m = p.matcher(id);
    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        String resourceTypeName = DefaultResourceDao.decode(m.group(1));
        String resourceName = DefaultResourceDao.decode(m.group(2));

        try {
            if (topLevelResource == null) {
                topLevelResource = getTopLevelResource(resourceTypeName, resourceName);
            } else {
                return getChildResourceList(topLevelResource);
            }
        } catch (Throwable e) {
            throw new ObjectRetrievalFailureException(OnmsResource.class, id,
                    "Could not get resource for resource ID '" + id + "'", e);
        }

        m.appendReplacement(sb, "");
    }

    m.appendTail(sb);

    if (sb.length() > 0) {
        throw new IllegalArgumentException(
                "resource ID '" + id + "' does not match pattern '" + p.toString() + "' at '" + sb + "'");
    }
    return null;
}

From source file:hydrograph.ui.dataviewer.filter.FilterHelper.java

/**
 * Gets the condition.//from  www  . j av a2  s  .  c om
 * 
 * @param conditionsList
 *            the conditions list
 * @param fieldsAndTypes
 *            the fields and types
 * @param groupSelectionMap
 *            the group selection map
 * @param isDisplayPressed
 *            the is display pressed
 * @return the condition
 */
public StringBuffer getCondition(final List<Condition> conditionsList, final Map<String, String> fieldsAndTypes,
        final Map<Integer, List<List<Integer>>> groupSelectionMap, boolean isDisplayPressed) {

    //put number of elements in the list
    //1 2 3 4 5
    List<String> actualStringList = new LinkedList<>();
    for (int conditionIndex = 0; conditionIndex < conditionsList.size(); conditionIndex++) {
        actualStringList.add(conditionIndex, String.valueOf((conditionIndex)));
    }
    logger.trace(actualStringList.toString());
    //start adding brackets for grouping
    Set<Integer> treeSet = (Set<Integer>) groupSelectionMap.keySet();
    if (treeSet.size() > 0) {
        for (Integer position : treeSet) {
            List<List<Integer>> groupsInColumn = groupSelectionMap.get(position);
            for (int groupIndex = 0; groupIndex < groupsInColumn.size(); groupIndex++) {
                List<Integer> group = groupsInColumn.get(groupIndex);
                //add opening bracket before first element in the group
                if (!group.isEmpty()) {
                    Integer firstItem = group.get(0);
                    Integer firstItemIndex = actualStringList.indexOf(String.valueOf(firstItem));
                    actualStringList.add(firstItemIndex, FilterConstants.OPEN_BRACKET);
                    //add closing bracket after last element in the group                     
                    Integer lastItem = group.get(group.size() - 1);
                    Integer lastItemIndex = actualStringList.indexOf(String.valueOf(lastItem));
                    actualStringList.add(lastItemIndex + 1, FilterConstants.CLOSE_BRACKET);
                }
            }
        }
    }

    //start adding relational operators
    int indexOfRelational = 1;
    //start from 2nd index
    for (int item = 1; item < conditionsList.size(); item++) {
        int indexOfItem = actualStringList.indexOf(String.valueOf(item));
        while (true) {
            if ((actualStringList.get(indexOfItem - 1)).matches(FilterConstants.REGEX_DIGIT)
                    || (actualStringList.get(indexOfItem - 1))
                            .equalsIgnoreCase(FilterConstants.CLOSE_BRACKET)) {
                actualStringList.add(indexOfItem,
                        conditionsList.get(indexOfRelational).getRelationalOperator());
                break;
            } else {
                indexOfItem = indexOfItem - 1;
            }
        }
        indexOfRelational += 1;
        logger.trace(actualStringList.toString());
    }

    StringBuffer buffer = new StringBuffer();
    for (int item = 0; item < conditionsList.size(); item++) {
        StringBuffer conditionString = new StringBuffer();

        Condition condition = conditionsList.get(item);
        if (StringUtils.equalsIgnoreCase(condition.getConditionalOperator(), FilterConstants.BETWEEN)
                || StringUtils.equalsIgnoreCase(condition.getConditionalOperator(),
                        FilterConstants.BETWEEN_FIELD)) {
            conditionString.append(condition.getFieldName()).append(FilterConstants.SINGLE_SPACE)
                    .append(condition.getConditionalOperator()).append(FilterConstants.SINGLE_SPACE)
                    .append(getConditionValue(condition.getFieldName(), condition.getValue1(),
                            condition.getConditionalOperator(), fieldsAndTypes, isDisplayPressed))
                    .append(FilterConstants.SINGLE_SPACE).append(FilterConstants.AND)
                    .append(FilterConstants.SINGLE_SPACE)
                    .append(getConditionValue(condition.getFieldName(), condition.getValue2(),
                            condition.getConditionalOperator(), fieldsAndTypes, isDisplayPressed));
        } else {
            conditionString.append(condition.getFieldName()).append(FilterConstants.SINGLE_SPACE)
                    .append(condition.getConditionalOperator()).append(FilterConstants.SINGLE_SPACE)
                    .append(getConditionValue(condition.getFieldName(), condition.getValue1(),
                            condition.getConditionalOperator(), fieldsAndTypes, isDisplayPressed));
        }
        int index = actualStringList.indexOf(String.valueOf(item));
        actualStringList.set(index, conditionString.toString());
    }

    for (String item : actualStringList) {
        buffer.append(item + FilterConstants.SINGLE_SPACE);
    }

    Pattern p = Pattern.compile("\\(Field\\)");
    Matcher m = p.matcher(buffer);
    StringBuffer temp = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(temp, "");
    }
    m.appendTail(temp);
    buffer = new StringBuffer(temp);
    return buffer;
}