Example usage for java.util.regex Matcher replaceFirst

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

Introduction

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

Prototype

public String replaceFirst(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces the first subsequence of the input sequence that matches the pattern with the result of applying the given replacer function to the match result of this matcher corresponding to that subsequence.

Usage

From source file:org.pentaho.reporting.platform.plugin.output.PaginationControlWrapper.java

private static String embedCss(String pageContent) throws IOException {
    Matcher cssLinkMatcher = CSS.matcher(pageContent);
    while (cssLinkMatcher.find() && cssLinkMatcher.groupCount() > 1) {
        final String cssContent = getSolutionDirFileContent(STAGING_PATH + cssLinkMatcher.group(2));
        pageContent = cssLinkMatcher.replaceFirst("<style>\n" + cssContent + "\n</style>");
        cssLinkMatcher = CSS.matcher(pageContent);
    }/*from  w w  w  .j av  a  2  s.  com*/
    return pageContent;
}

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

/**
 * Checks and removes base tags such as:
 * <base href= />/* ww  w .j a v a2  s.  com*/
 * @param value HTML source
 * @return html with base tag removed
 */
public static String stripBaseTag(String value) {
    if (null == value) {
        throw new IllegalArgumentException("input required");
    }
    //Extract all source files
    Matcher matchSrc = BASE_TAG.matcher(value);
    return matchSrc.replaceFirst("");
}

From source file:org.pentaho.reporting.platform.plugin.output.PaginationControlWrapper.java

private static String replaceImgSrc(String pageContent) throws IOException {
    String fullyQualifiedServerUrl = PentahoSystem.getApplicationContext().getFullyQualifiedServerURL();
    URL url = new URL(fullyQualifiedServerUrl);
    String garbage = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort();
    String prefix = fullyQualifiedServerUrl.substring(garbage.length(), fullyQualifiedServerUrl.length() - 1);

    Matcher imgLinkMatcher = IMG.matcher(pageContent);
    while (imgLinkMatcher.find() && imgLinkMatcher.groupCount() > 1) {
        String imgContent = imgLinkMatcher.group(0);
        imgContent = imgContent.replace(imgLinkMatcher.group(2), prefix);
        pageContent = imgLinkMatcher.replaceFirst(imgContent);
        imgLinkMatcher = IMG.matcher(pageContent);
    }//  w w w  .j  a  va 2s. co m
    return pageContent;
}

From source file:py.una.pol.karaku.util.ELHelper.java

/**
 * Dada una expresin del tipo//w w w  .  jav  a  2 s.c o m
 * 
 * <pre>
 *       #{controller.bean.field}
 * </pre>
 * 
 * Retorna el {@link Field} donde se almacenara el campo field, notar que es
 * a nivel de {@link Field}, es decir, requiere que el getter y el setter,
 * tengan el mismo nombre (getField, setField), no sirve para campos que no
 * cumplan esta condicion.
 * 
 * @param beanExpression
 *            expresin con el formato de
 *            {@link #EXTRACT_FIELD_FROM_EXPRESSION_REGEX}
 * @return {@link Field} del atributo
 * @since 1.3.2
 */
public static Field getFieldByExpression(String beanExpression) {

    // abre y cierra un parntesis, se utiliza para definir si utiliza algn
    // mtodo.
    if (beanExpression.indexOf('(') != -1 && beanExpression.indexOf(')') != -1) {
        return null;
    }
    FacesContext context = FacesContext.getCurrentInstance();
    Matcher ma = getPattern().matcher(beanExpression);
    if (ma.matches()) {
        String withoutField = ma.replaceFirst("$1$3");
        String field = ma.replaceFirst("$2");
        Object bean;
        try {
            bean = context.getApplication().getExpressionFactory()
                    .createValueExpression(context.getELContext(), withoutField, Object.class)
                    .getValue(context.getELContext());
        } catch (ELException el) {
            // TODO mejorar para tener en cuenta cuando la expresin se
            // refiere a un Vector.
            // Utilizar la expresin regular
            // (#\{.*)\.([a-zA-Z]*|[a-zA-Z]*\[[a-zA-Z\.]*\])(\})
            // See http://www.regexplanet.com/advanced/java/index.html
            LOG.info(CAN_NOT_FIND_THE_FIELD_OF_THE_EXPRESSION, beanExpression, el);
            return null;
        }
        if (bean != null) {
            Field f;
            try {
                f = bean.getClass().getDeclaredField(field);
            } catch (Exception e) {
                try {
                    LOG.trace("Can't get field by reflection, trying using proxies", e);
                    f = getFieldForce(field, bean.getClass());
                } catch (Exception e2) {
                    LOG.debug(CAN_NOT_FIND_THE_FIELD_OF_THE_EXPRESSION, beanExpression, e2);
                    return null;
                }
            }
            return f;
        }
    }
    return null;
}

From source file:org.lockss.plugin.associationforcomputingmachinery.AssociationForComputingMachineryXmlMetadataExtractorFactory.java

/**
 * Uses a CachedUrl assumed to be in the directory of the metadata file to find the
 * pathname for the metadata file (and return it)
 * @param cu - address of a sibling of the metadata file
 * @return the metadata file's pathname/*from w w w  . j  a  v  a2s. c  om*/
 */
private static String getMetadataFile(CachedUrl cu) {
    Pattern pattern = Pattern.compile(
            "(http://clockss-ingest.lockss.org/sourcefiles/[^/]+/[\\d]+/[^/]+/)([^/]+)(/[^/]+.xml)",
            Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(cu.getUrl());
    return matcher.replaceFirst("$1$2/$2.xml");
}

From source file:org.xwiki.rendering.parser.xwiki10.util.CleanUtil.java

public static String extractVelocity(CharSequence content, FilterContext filterContext, boolean protect,
        boolean inline) {
    String cleanedContent = content.toString();

    Matcher velocityOpenMatcher = VelocityFilter.VELOCITYOPEN_PATTERN.matcher(cleanedContent);
    boolean velocityOpen = velocityOpenMatcher.find();
    cleanedContent = velocityOpenMatcher.replaceFirst("");
    Matcher velocityCloseMatcher = VelocityFilter.VELOCITYCLOSE_PATTERN.matcher(cleanedContent);
    boolean velocityClose = velocityCloseMatcher.find();
    cleanedContent = velocityCloseMatcher.replaceFirst("");

    StringBuffer buffer = new StringBuffer();

    boolean multilines = filterContext.unProtect(cleanedContent).indexOf("\n") != -1;

    if (velocityOpen) {
        VelocityFilter.appendVelocityOpen(buffer, filterContext, multilines);
    }//w  ww  . j  av  a  2  s  .  c om

    if (protect) {
        buffer.append(filterContext.addProtectedContent(cleanedContent, inline));
    } else {
        buffer.append(cleanedContent);
    }

    if (velocityClose) {
        VelocityFilter.appendVelocityClose(buffer, filterContext, multilines);
    }

    return buffer.toString();
}

From source file:org.grycap.gpf4med.util.URLUtils.java

/**
 * Parses a URL from a String. This method supports file-system paths 
 * (e.g. /foo/bar).//  ww w.  ja  v a  2  s.  co m
 * @param str String representation of an URL.
 * @return an URL.
 * @throws IOException If an input/output error occurs.
 */
public static URL parseURL(final String str) throws MalformedURLException {
    URL url = null;
    if (StringUtils.isNotBlank(str)) {
        try {
            url = new URL(str);
        } catch (MalformedURLException e) {
            url = null;
            if (!str.matches("^[a-zA-Z]+[/]*:[^\\\\]")) {
                // convert path to UNIX path
                String path = FilenameUtils.separatorsToUnix(str.trim());
                final Pattern pattern = Pattern.compile("^([a-zA-Z]:/)");
                final Matcher matcher = pattern.matcher(path);
                path = matcher.replaceFirst("/");
                // convert relative paths to absolute paths
                if (!path.startsWith("/")) {
                    path = path.startsWith("~") ? path.replaceFirst("~", System.getProperty("user.home"))
                            : FilenameUtils.concat(System.getProperty("user.dir"), path);
                }
                // normalize path
                path = FilenameUtils.normalize(path, true);
                if (StringUtils.isNotBlank(path)) {
                    url = new File(path).toURI().toURL();
                } else {
                    throw new MalformedURLException("Invalid path: " + path);
                }
            } else {
                throw e;
            }
        }
    }
    return url;
}

From source file:org.webcurator.ui.tools.controller.BrowseHelper.java

/**
 * Gets the absolute URL based on the URL string and the current resource.
 * This method handles relative URLs./*from w  w  w. j a v a2 s.c  om*/
 * 
 * @param currentUrl The URL of the current resource.
 * @param subUrl The URL to be rewritten.
 * @return The absolute URL of the resource.
 */
public static String getAbsURL(String currentUrl, String subUrl) {
    String replacedUrl = subUrl.trim();
    try {
        UURI base = UURIFactory.getInstance(currentUrl);
        UURI absUURI = UURIFactory.getInstance(base, replacedUrl);

        // does subUrl have a fragment (a.k.a a ref or jump tag) ?
        URI uri = null;
        try {
            uri = new URI(replacedUrl);
        } catch (URISyntaxException uriEx) {
            //Tried to parse and failed, attempt to URL encode
            String strUri = URLEncoder.encode(replacedUrl, "UTF-8");
            //put the fragment marker back (if there was one)
            Pattern p = Pattern.compile("%23");
            Matcher m = p.matcher(strUri);
            uri = new URI(m.replaceFirst("#"));
        }

        String fragment = uri.getFragment();
        if (fragment == null) {
            return absUURI.getEscapedURI();
        } else {
            return absUURI.getEscapedURI() + "#" + fragment;
        }
    } catch (Exception ex) {
        log.error("Error parsing URI '" + replacedUrl + "': ", ex);
        return null;
    }
}

From source file:org.oscarehr.decisionSupport.model.conditionValue.DSValue.java

public static DSValue createDSValue(String typeOperatorValueUnit) {
    boolean processStatement = true;
    Pattern stringQuotePattern = Pattern.compile("'.+?'");
    if (stringQuotePattern.matcher(typeOperatorValueUnit).find()) {
        typeOperatorValueUnit = typeOperatorValueUnit.replaceAll("'", "");
        processStatement = false;/* w  ww  .  ja va 2s  . c om*/
    }
    DSValue returnDsValue;
    int typeSeparatorIndex = indexOfNotQuoted(typeOperatorValueUnit, ":");
    String valueStr;
    String typeStr = null;
    String operator = null;
    String unit = null;

    //take out the type i.e. 'atc:'
    if (typeSeparatorIndex == -1) {
        valueStr = typeOperatorValueUnit.trim();
    } else {
        typeStr = typeOperatorValueUnit.substring(0, typeSeparatorIndex).trim();
        valueStr = typeOperatorValueUnit.substring(typeSeparatorIndex + 1).trim();
    }

    Matcher operatorMatcher = Pattern.compile("[<>=-]+").matcher(valueStr);

    //find operator
    if (processStatement && operatorMatcher.find()) {
        operator = operatorMatcher.group().trim();
        valueStr = operatorMatcher.replaceFirst("").trim();

        Matcher unitMatcher = Pattern.compile("([^\\s]+$)").matcher(valueStr);
        //must be trimmed
        if (valueStr.indexOf(" ") != -1) {
            unitMatcher.find();
            unit = unitMatcher.group().trim();
            valueStr = unitMatcher.replaceFirst("").trim();
        }

        DSValueStatement dsValue = new DSValueStatement();
        dsValue.setValueType(typeStr);
        dsValue.setValue(valueStr);
        dsValue.setOperator(operator);
        dsValue.setValueUnit(unit);
        returnDsValue = dsValue;
    } else {
        DSValueString dsValue = new DSValueString();
        dsValue.setValueType(typeStr);
        dsValue.setValue(valueStr);
        returnDsValue = dsValue;
    }
    _log.debug("DSValue type: " + returnDsValue.getValueType() + " operator: " + returnDsValue.getValue()
            + " unit: " + returnDsValue.getValueUnit() + " object type: " + returnDsValue.getClass().getName());
    return returnDsValue;
}

From source file:org.xlcloud.rest.client.config.LoggingFilterHelper.java

public static String maskPath(String path) {
    for (MaskedPath maskedPath : MASKED_PATHS) {
        Matcher matcher = maskedPath.path.matcher(path);
        if (matcher.find()) {
            return matcher.replaceFirst("$1" + escapeForReplace(maskPartially(matcher.group(2))) + "$3");
        }// ww w  .j  av  a  2 s.  c o  m
    }
    return path;
}