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:com.datumbox.framework.common.utilities.PHPMethods.java

/**
 * Matches a string with a pattern and replaces the matched components with 
 * a provided string./*from   ww w .  j a  v a  2  s  . c o  m*/
 * 
 * @param pattern
 * @param replacement
 * @param subject
 * @return 
 */
public static String preg_replace(Pattern pattern, String replacement, String subject) {
    Matcher m = pattern.matcher(subject);
    StringBuffer sb = new StringBuffer(subject.length());
    while (m.find()) {
        m.appendReplacement(sb, replacement);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:jetbrick.tools.chm.reader.AnchorNameManager.java

public static void addAnchor(File file, String encoding) throws IOException {
    String html = FileUtils.readFileToString(file, encoding);
    html = html.replace('$', '\uFFE5');

    Pattern p = Config.style.getAnchorNameRegex();
    Matcher m = p.matcher(html);

    int findCount = 0;
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        findCount++;//from w w w.  jav a2s. c o  m
        String anchor = m.group(1);
        // String oldAnchor = m.group();
        String oldAnchor = "<A HH=\"1\" NAME=\"" + anchor + "\">";
        String newAnchor = "<A HH=\"1\" NAME=\"" + getNewAnchorName(anchor) + "\"></A>";
        m.appendReplacement(sb, newAnchor + oldAnchor);
    }
    m.appendTail(sb);

    System.out.println("addAnchor(" + findCount + ") : " + file);

    if (findCount > 0) {
        html = sb.toString().replace('\uFFE5', '$');
        FileUtils.writeStringToFile(file, html, encoding);
    }
    html = null;
}

From source file:info.magnolia.cms.util.LinkUtil.java

/**
 * Transforms all the links to the magnolia format. Used during storing.
 * @param str html//from  w  ww . ja  va 2s .  c  o  m
 * @return html with changed hrefs
 */
public static String convertAbsoluteLinksToUUIDs(String str) {
    // get all link tags
    Matcher matcher = linkPattern.matcher(str);
    StringBuffer res = new StringBuffer();
    while (matcher.find()) {
        String path = matcher.group(2);
        String uuid = makeUUIDFromAbsolutePath(path);
        matcher.appendReplacement(res, "$1\\${link:{" //$NON-NLS-1$
                + "uuid:{" //$NON-NLS-1$
                + uuid + "}," //$NON-NLS-1$
                + "repository:{website}," //$NON-NLS-1$
                + "workspace:{default}," //$NON-NLS-1$
                + "path:{" //$NON-NLS-1$
                + path + "}}}$3"); //$NON-NLS-1$
    }
    matcher.appendTail(res);
    return res.toString();
}

From source file:org.openhab.binding.ACDBCommon.db.DBManager.java

/**
 * execute update/*from w  ww . j  a  va  2s.com*/
 *
 * @param updateSql
 * @param sqlParam
 * @throws Exception
 */
private static void update(ServerInfo server, String updateSql, HashMap<String, String> sqlParam)
        throws Exception {
    Pattern sqlPattern = Pattern.compile("(\\?)");

    // analyze SQL statement
    Matcher matcher = sqlPattern.matcher(updateSql);
    StringBuffer newSql = new StringBuffer();

    while (matcher.find()) {
        String columnName = matcher.group(0);
        if (StringUtils.isNotEmpty(columnName)) {
            matcher.appendReplacement(newSql, sqlParam.get("value"));
        }
    }
    matcher.appendTail(newSql);
    logger.debug("### sql:{}", newSql);

    try (PreparedStatement stmt = server.getConnection().prepareStatement(newSql.toString())) {
        stmt.executeUpdate();
    }
}

From source file:com.csc.fi.ioapi.utils.LDHelper.java

public static String expandSparqlQuery(String query, Map<String, String> prefix_map) {

    for (Map.Entry<String, String> namespaces : prefix_map.entrySet()) {
        StringBuffer sb = new StringBuffer();
        /* Find curies starting with whitespace */
        String prefiz = " " + namespaces.getKey().concat(":");
        String REGEX = prefiz + "\\w*\\b";
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(query);

        while (m.find()) {
            StringBuffer replacement = new StringBuffer();
            replacement.append(" <").append(m.group().replace(prefiz, namespaces.getValue())).append(">");
            m.appendReplacement(sb, replacement.toString());
        }//ww w. j  a  v  a 2s .  c  o m

        m.appendTail(sb);
        query = sb.toString();

    }

    return query;
}

From source file:com.igormaznitsa.mindmap.model.ModelUtils.java

@Nonnull
public static String unescapeMarkdownStr(@Nonnull final String text) {
    String unescaped = UNESCAPE_BR.matcher(text).replaceAll("\n"); //NOI18N
    final StringBuffer result = new StringBuffer(text.length());
    final Matcher escaped = MD_ESCAPED_PATTERN.matcher(unescaped);
    while (escaped.find()) {
        final String group = escaped.group(1);
        escaped.appendReplacement(result, Matcher.quoteReplacement(group.substring(1)));
    }/*from www.j ava  2 s  .c  o m*/
    escaped.appendTail(result);
    return result.toString();
}

From source file:com.addthis.hydra.job.alert.JobAlertUtil.java

/**
 * Split a path up and replace any {{now-1}}-style elements with the YYMMDD equivalent.
 * {{now-1h}} subtracts one hour from the current time and returns a YYMMDDHH formatted string.
 *
 * @param path The input path to process
 * @return The path with the relevant tokens replaced
 *///w w  w .ja  va  2 s  .c o m
@VisibleForTesting
static String expandDateMacro(String path) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = DATE_MACRO_PATTERN.matcher(path);
    while (matcher.find()) {
        if (matcher.group(3) != null) {
            String match = "{{now" + matcher.group(2) + Strings.nullToEmpty(matcher.group(4)) + "}}";
            matcher.appendReplacement(sb,
                    DateUtil.getDateTime(ymdhFormatter, match, true).toString(ymdhFormatter));
        } else {
            String match = matcher.group();
            matcher.appendReplacement(sb,
                    DateUtil.getDateTime(ymdFormatter, match, false).toString(ymdFormatter));
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.etudes.component.app.jforum.util.html.SafeHtml.java

/**
 * removes existing target attribute in the anchor tag and adds target="_blank"
 * /*  ww w  .java2s . c  o m*/
 * @param contents
 *        Post contest
 * 
 * @return Modified content with target="_blank" in anchor tags
 */
public static String addAnchorTarget(String contents) {
    if (contents == null) {
        return null;
    }

    StringBuffer sb = new StringBuffer();

    Pattern p = Pattern.compile("<(a)([^>]+)>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
    Matcher m = p.matcher(contents);

    while (m.find()) {
        if (m.groupCount() == 2) {
            String group1 = m.group(1);
            String group2 = m.group(2);
            String modGroup2 = group2.replaceAll("(target\\s*=\\s*[\"\'][^\"\']*[\"\']\\s*)?", "");

            String modString = "<" + group1 + " target=\"_blank\" " + modGroup2 + ">";

            m.appendReplacement(sb, Matcher.quoteReplacement(modString));
        }
    }

    m.appendTail(sb);

    return sb.toString();
}

From source file:com.age.core.orm.hibernate.HibernateDao.java

private static String removeOrders(String hql) {
    Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(hql);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, "");
    }/*from  www. j  a va  2s.c  o m*/
    m.appendTail(sb);
    return sb.toString();
}

From source file:net.sf.jabref.external.RegExpFileSearch.java

/**
 * The actual work-horse. Will find absolute filepaths starting from the
 * given directory using the given regular expression string for search.
 *///from w w  w . j  a v  a2s  .com
private static List<File> findFile(BibEntry entry, File directory, String file, String extensionRegExp) {

    List<File> res = new ArrayList<>();

    File actualDirectory;
    if (file.startsWith("/")) {
        actualDirectory = new File(".");
        file = file.substring(1);
    } else {
        actualDirectory = directory;
    }

    // Escape handling...
    Matcher m = ESCAPE_PATTERN.matcher(file);
    StringBuffer s = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(s, m.group(1) + '/' + m.group(2));
    }
    m.appendTail(s);
    file = s.toString();
    String[] fileParts = file.split("/");

    if (fileParts.length == 0) {
        return res;
    }

    for (int i = 0; i < (fileParts.length - 1); i++) {

        String dirToProcess = fileParts[i];
        dirToProcess = expandBrackets(dirToProcess, entry, null);

        if (dirToProcess.matches("^.:$")) { // Windows Drive Letter
            actualDirectory = new File(dirToProcess + '/');
            continue;
        }
        if (".".equals(dirToProcess)) { // Stay in current directory
            continue;
        }
        if ("..".equals(dirToProcess)) {
            actualDirectory = new File(actualDirectory.getParent());
            continue;
        }
        if ("*".equals(dirToProcess)) { // Do for all direct subdirs

            File[] subDirs = actualDirectory.listFiles();
            if (subDirs != null) {
                String restOfFileString = StringUtil.join(fileParts, "/", i + 1, fileParts.length);
                for (File subDir : subDirs) {
                    if (subDir.isDirectory()) {
                        res.addAll(findFile(entry, subDir, restOfFileString, extensionRegExp));
                    }
                }
            }
        }
        // Do for all direct and indirect subdirs
        if ("**".equals(dirToProcess)) {
            List<File> toDo = new LinkedList<>();
            toDo.add(actualDirectory);

            String restOfFileString = StringUtil.join(fileParts, "/", i + 1, fileParts.length);

            while (!toDo.isEmpty()) {

                // Get all subdirs of each of the elements found in toDo
                File[] subDirs = toDo.remove(0).listFiles();
                if (subDirs == null) {
                    continue;
                }

                toDo.addAll(Arrays.asList(subDirs));

                for (File subDir : subDirs) {
                    if (!subDir.isDirectory()) {
                        continue;
                    }
                    res.addAll(findFile(entry, subDir, restOfFileString, extensionRegExp));
                }
            }

        } // End process directory information
    }

    // Last step: check if the given file can be found in this directory
    String filePart = fileParts[fileParts.length - 1].replace("[extension]", EXT_MARKER);
    String filenameToLookFor = expandBrackets(filePart, entry, null).replaceAll(EXT_MARKER, extensionRegExp);
    final Pattern toMatch = Pattern.compile('^' + filenameToLookFor.replaceAll("\\\\\\\\", "\\\\") + '$',
            Pattern.CASE_INSENSITIVE);

    File[] matches = actualDirectory.listFiles((arg0, arg1) -> {
        return toMatch.matcher(arg1).matches();
    });
    if ((matches != null) && (matches.length > 0)) {
        Collections.addAll(res, matches);
    }
    return res;
}