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:net.jawr.web.resource.bundle.factory.util.PathNormalizer.java

/**
 * Returns the relative path of an url to go back to the root. For example :
 * if the url path is defined as "/cssServletPath/css/myStyle.css" ->
 * "../../"/*  w w  w . ja va 2s  . co  m*/
 * 
 * @param url the requested url
 * @return the relative path of an url to go back to the root.
 */
public static String getRootRelativePath(String url) {

    Matcher matcher = URL_SEPARATOR_PATTERN.matcher(url);
    StringBuffer result = new StringBuffer();
    boolean first = true;
    while (matcher.find()) {
        if (first) {
            matcher.appendReplacement(result, "");
            first = false;
        } else {
            matcher.appendReplacement(result, ROOT_REPLACE_PATTERN);
        }
    }

    return result.toString();
}

From source file:com.dtolabs.rundeck.core.dispatcher.DataContextUtils.java

/**
 * Replace the embedded  properties of the form '${key.name}' in the input Strings with the value from the data
 * context/*  w  w  w  . j a v  a 2  s. com*/
 *
 *
 * @param input input string
 * @param data  data context map
 *              @param converter converter to encode/convert the expanded values
 *
 * @param failOnUnexpanded
 * @return string with values substituted, or original string
 */
public static String replaceDataReferences(final String input, final Map<String, Map<String, String>> data,
        final Converter<String, String> converter, boolean failOnUnexpanded, boolean blankIfUnexpanded) {
    if (null == data) {
        return input;
    }
    final Pattern p = Pattern.compile(PROPERTY_REF_REGEX);
    final Matcher m = p.matcher(input);
    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        final String key = m.group(1);
        final String nm = m.group(2);
        if (null != key && null != nm && null != data.get(key) && null != data.get(key).get(nm)) {
            String value = data.get(key).get(nm);
            if (null != converter) {
                value = converter.convert(value);
            }
            m.appendReplacement(sb, Matcher.quoteReplacement(value));
        } else if (failOnUnexpanded && null != key && null != nm
                && (null == data.get(key) || null == data.get(key).get(nm))) {
            throw new UnresolvedDataReferenceException(input, m.group());
        } else if (blankIfUnexpanded) {
            m.appendReplacement(sb, "");
        } else {
            String value = m.group(0);
            if (null != converter) {
                value = converter.convert(value);
            }
            m.appendReplacement(sb, Matcher.quoteReplacement(value));
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.hexidec.ekit.component.HTMLTableUtilities.java

public static String separaTabelasDeParagrafos(String str) {

    Matcher m = pTabelaEmParagrafo.matcher(str);
    if (!m.find()) {
        return str;
    }//from  w w w .ja va 2  s  . c o  m

    StringBuffer sb = new StringBuffer();
    StringBuffer trecho;
    String pOpen, strBefore, tOpen, tBody, strAfter;
    do {
        trecho = new StringBuffer();
        pOpen = m.group(1);
        strBefore = m.group(2);
        tOpen = m.group(3);
        tBody = m.group(4);
        strAfter = m.group(5);

        if (!StringUtils.isEmpty(strBefore.trim())) {
            trecho.append(pOpen);
            trecho.append(strBefore);
            trecho.append("</p>");
        }
        trecho.append(tOpen);
        trecho.append(tBody);
        trecho.append("</table>");
        if (!StringUtils.isEmpty(strAfter.trim())) {
            trecho.append(pOpen);
            trecho.append(strAfter);
            trecho.append("</p>");
        }

        m.appendReplacement(sb, Matcher.quoteReplacement(trecho.toString()));

    } while (m.find());

    m.appendTail(sb);

    return sb.toString();
}

From source file:org.j2eespider.util.BuildManagerUtil.java

/**
 * Process a path, and can return a list of path, according to the variable (she will go a list of values).
 * @param path/*from  w  w  w  . j  av a2  s.co  m*/
 * @return
 * @throws Exception 
 */
public static String[] processPathVariables(String path, TemplateDataGroup dataGroup) throws Exception {
    StringBuffer replaceResult = new StringBuffer();

    //---SEARCH FOR stringUtils
    String regexStringUtils = "\\$\\{stringUtils.*?\\(.*?\\)\\}";

    // Compile regular expression
    Pattern patternStringUtils = Pattern.compile(regexStringUtils);

    // Create Matcher
    Matcher matcherStringUtils = patternStringUtils.matcher(path);

    // Find occurrences
    while (matcherStringUtils.find()) {
        String variable = matcherStringUtils.group();

        // Variables
        HashMap<String, Object> velocityVariables = new HashMap<String, Object>();
        velocityVariables.put("data", dataGroup);

        TemplateEngine templateEngine = VelocityTemplateEngine.getInstance();
        String vmResult = templateEngine.runInLine(variable, velocityVariables);
        matcherStringUtils.appendReplacement(replaceResult, vmResult);
    }
    matcherStringUtils.appendTail(replaceResult);
    path = replaceResult.toString();
    replaceResult = new StringBuffer();

    //---SEARCH FOR VARIABLE data
    String regexVariable = "\\$\\{.*?\\}";
    Map<String, String[]> mapVariableToDuplicateResult = new HashMap<String, String[]>();

    // Compile regular expression
    Pattern patternVariable = Pattern.compile(regexVariable);

    // Create Matcher
    Matcher matcherVariable = patternVariable.matcher(path);

    // Find occurrences
    while (matcherVariable.find()) {
        String variable = matcherVariable.group();
        variable = variable.replaceAll("\\$\\{", "").replaceAll("\\}", "");
        //variable = variable.substring(2, variable.length()-1); //remove ${ }

        //replace a list of matches
        Map<String, Object> objects = new HashMap<String, Object>();
        objects.put("data.config", dataGroup.getConfig());
        objects.put("data.crud", dataGroup.getCrud());
        objects.put("data.bundle", dataGroup.getBundle());

        String[] values = BuildManagerUtil.readValue(variable, objects);
        if (values.length == 1) { //one value
            matcherVariable.appendReplacement(replaceResult, values[0]);
        } else if (values.length > 1) { //list of values
            mapVariableToDuplicateResult.put(variable, values); //guarda todas as vriaveis do tipo LIST do path
        }
    }
    matcherVariable.appendTail(replaceResult);

    //s  permitido uma vriavel do tipo list no nas vriaveis
    if (mapVariableToDuplicateResult.size() > 1) {
        throw new Exception("Template error: Alone it is permitted one variable of the kind LIST in the paths");
    }

    //return results
    //process list of variables, or return
    if (mapVariableToDuplicateResult.size() == 1) { //rules of the list of values for the variable (existe uma vriavel do tipo list)
        List<String> results = new ArrayList<String>(); //grava os resultados
        for (String variable : mapVariableToDuplicateResult.keySet()) { //loop nas variaveis do tipo list (que  uma s)
            String[] values = mapVariableToDuplicateResult.get(variable); //pega os valores vlidos para a variavel do tipo list (valores que devem entrar no lugar da vriavel list)
            for (String value : values) {
                results.add(replaceResult.toString().replaceAll("\\$\\{" + variable + "\\}", value)); //adiciona um path novo para cada valor que tem que ser substituido
            }
        }

        //transforma o list em array de string
        String[] values = new String[results.size()];
        for (int i = 0; i < results.size(); i++) {
            values[i] = results.get(i).toString();
        }
        return values;
    } else if (mapVariableToDuplicateResult.size() == 0 && !replaceResult.toString().equals("")) { //there is does not list of values, is simple replace
        return new String[] { replaceResult.toString() };
    }

    //no encontrou resultados / not matches found
    return new String[] { path };
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param input/*  www. ja v a  2s  .c  o m*/
 * @return String
 */
public static String toLowerHTML(String input) {
    Pattern genericPattern = Pattern.compile(GENERIC_TAG_PATTERN);
    Matcher genericMatcher = genericPattern.matcher(input);
    StringBuffer inputBuffer = new StringBuffer();

    while (genericMatcher.find()) {
        String openBracket = genericMatcher.group(1);
        String slash = genericMatcher.group(2);
        String tagName = genericMatcher.group(3);
        String trailing = genericMatcher.group(4);
        if (!"HTML".equals(tagName)) {
            tagName = tagName.toLowerCase();
        }
        genericMatcher.appendReplacement(inputBuffer,
                escapeBackreference(openBracket + slash + tagName + trailing));
    }
    genericMatcher.appendTail(inputBuffer);

    return inputBuffer.toString();
}

From source file:org.apache.flink.table.runtime.functions.SqlFunctionUtils.java

/**
 * Returns a string resulting from replacing all substrings that match the regular
 * expression with replacement./*from w w w . jav a  2s .c om*/
 */
public static String regexpReplace(String str, String regex, String replacement) {
    if (regex.isEmpty()) {
        return str;
    }
    try {
        // we should use StringBuffer here because Matcher only accept it
        StringBuffer sb = new StringBuffer();
        Matcher m = REGEXP_PATTERN_CACHE.get(regex).matcher(str);
        while (m.find()) {
            m.appendReplacement(sb, replacement);
        }
        m.appendTail(sb);
        return sb.toString();
    } catch (Exception e) {
        LOG.error(String.format("Exception in regexpReplace('%s', '%s', '%s')", str, regex, replacement), e);
        // return null if exception in regex replace
        return null;
    }
}

From source file:net.opentsdb.tools.ConfigArgP.java

/**
 * Replaces all matched tokens with the matching system property value or a configured default
 * @param text The text to process//w w w.  ja v a2  s . c om
 * @return The substituted string
 */
public static String tokenReplaceSysProps(CharSequence text) {
    if (text == null)
        return null;
    Matcher m = SYS_PROP_PATTERN.matcher(text);
    StringBuffer ret = new StringBuffer();
    while (m.find()) {
        String replacement = decodeToken(m.group(1), m.group(2) == null ? "<null>" : m.group(2));
        if (replacement == null) {
            throw new IllegalArgumentException(
                    "Failed to fill in SystemProperties for expression with no default [" + text + "]");
        }
        if (IS_WINDOWS) {
            replacement = replacement.replace(File.separatorChar, '/');
        }
        m.appendReplacement(ret, replacement);
    }
    m.appendTail(ret);
    return ret.toString();
}

From source file:org.alfresco.selenium.FetchCSS.java

/**
 * Extract additional content found in css.
 * @param source css //  ww  w  .ja va  2 s  .  c  om
 * @return collection of files to get 
 * @throws IOException if error
 */
public static void getCSSFiles(File file, WebDriver driver) throws IOException {
    if (file == null) {
        throw new IllegalArgumentException("CSS source is required");
    }
    String source = FileUtils.readFileToString(file);
    source = source.replaceAll("}", "}\n");
    String domain = getHost(driver);
    CloseableHttpClient client = FetchHttpClient.getHttpClient(driver);
    StringBuffer sb = new StringBuffer();
    try {
        //Extract all source files
        Matcher matchSrc = CSS_BACKGOUND_IMG_PATTERN.matcher(source);
        while (matchSrc.find()) {
            //Change extracted source file to absolute urls 
            String fileSourceOri = matchSrc.group(0);
            String fileSource = fileSourceOri.replaceAll("\"", "");
            if (!fileSource.startsWith("data:image")) {
                if (fileSource.startsWith("//")) {
                    fileSource = fileSource.replace("//", "http://");
                } else if (fileSource.startsWith("/")) {
                    fileSource = fileSource.replaceFirst("/", domain + "/");
                }
                //Add to collection of paths for downloading
                getCssFile(fileSource, fileSourceOri, client);
            }
            //Amend path to point to file in the same directory
            if (!fileSourceOri.startsWith("//") || fileSourceOri.startsWith("\"/")) {
                String t = fileSourceOri.replaceFirst("\"/", "\"");
                matchSrc.appendReplacement(sb, t);
            } else {

                matchSrc.appendReplacement(sb, fileSourceOri);
            }
        }
        if (sb.length() < 1) {
            FileUtils.writeStringToFile(file, source);
        } else {
            FileUtils.writeStringToFile(file, sb.toString());
        }

    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:net.opentsdb.tools.ConfigArgP.java

/**
 * Evaluates JS expressions defines as configuration values
 * @param text The value of a configuration item to evaluate for JS expressions
 * @return The passed value with any embedded JS expressions evaluated and replaced
 *///from w w  w .jav  a  2s . c  o m
public static String evaluate(CharSequence text) {
    if (text == null)
        return null;
    Matcher m = JS_PATTERN.matcher(text);
    StringBuffer ret = new StringBuffer();
    final boolean isNas = scriptEngine.getFactory().getEngineName().toLowerCase().contains("nashorn");
    while (m.find()) {
        String source = (isNas ? "load(\"nashorn:mozilla_compat.js\");\nimportPackage(java.lang); "
                : "\nimportPackage(java.lang); ") + m.group(1);
        try {

            Object obj = scriptEngine.eval(source);
            if (obj != null) {
                //log("Evaled [%s] --> [%s]", source, obj);
                m.appendReplacement(ret, obj.toString());
            } else {
                m.appendReplacement(ret, "");
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
            throw new IllegalArgumentException("Failed to evaluate expression [" + text + "]");
        }
    }
    m.appendTail(ret);
    return ret.toString();
}

From source file:org.kalypso.ui.editor.styleeditor.symbolizer.StringToParameterValueTypeConverter.java

private String matchCurrentText(final Matcher matcher) {
    final StringBuffer buf = new StringBuffer();
    matcher.appendReplacement(buf, StringUtils.EMPTY);
    return buf.toString();
}