Example usage for java.util.regex Pattern matches

List of usage examples for java.util.regex Pattern matches

Introduction

In this page you can find the example usage for java.util.regex Pattern matches.

Prototype

public static boolean matches(String regex, CharSequence input) 

Source Link

Document

Compiles the given regular expression and attempts to match the given input against it.

Usage

From source file:com.gemstone.gemfire.management.internal.cli.parser.preprocessor.PreprocessorUtils.java

/**
 * //w  ww.j  ava 2  s  . c o m
 * This function will trim the given input string. It will not only remove the
 * spaces and tabs at the end but also compress multiple spaces and tabs to a
 * single space
 * 
 * @param input
 *          The input string on which the trim operation needs to be performed
 * @param retainLineSeparator
 *          whether to retain the line separator.
 * 
 * @return String
 */
public static TrimmedInput trim(final String input, final boolean retainLineSeparator) {
    if (input != null) {
        String inputCopy = input;
        StringBuffer output = new StringBuffer();
        // First remove the trailing white spaces, we do not need those
        inputCopy = StringUtils.stripEnd(inputCopy, null);
        // As this parser is for optionParsing, we also need to remove
        // the trailing optionSpecifiers provided it has previous
        // options. Remove the trailing LONG_OPTION_SPECIFIERs
        // in a loop. It is necessary to check for previous options for
        // the case of non-mandatory arguments.
        // "^(.*)(\\s-+)$" - something that ends with a space followed by a series of hyphens.
        while (Pattern.matches("^(.*)(\\s-+)$", inputCopy)) {
            inputCopy = StringUtils.removeEnd(inputCopy, SyntaxConstants.SHORT_OPTION_SPECIFIER);

            // Again we need to trim the trailing white spaces
            // As we are in a loop
            inputCopy = StringUtils.stripEnd(inputCopy, null);
        }
        // Here we made use of the String class function trim to remove the
        // space and tabs if any at the
        // beginning and the end of the string
        int noOfSpacesRemoved = 0;
        {
            int length = inputCopy.length();
            inputCopy = inputCopy.trim();
            noOfSpacesRemoved += length - inputCopy.length();
        }
        // Now we need to compress the multiple spaces and tabs to single space
        // and tabs but we also need to ignore the white spaces inside the
        // quotes and parentheses

        StringBuffer buffer = new StringBuffer();

        boolean startWhiteSpace = false;
        for (int i = 0; i < inputCopy.length(); i++) {
            char ch = inputCopy.charAt(i);
            buffer.append(ch);
            if (PreprocessorUtils.isWhitespace(ch)) {
                if (PreprocessorUtils.isSyntaxValid(buffer.toString())) {
                    if (startWhiteSpace) {
                        noOfSpacesRemoved++;
                    } else {
                        startWhiteSpace = true;
                        if (ch == '\n') {
                            if (retainLineSeparator) {
                                output.append("\n");
                            }
                        } else {
                            output.append(" ");
                        }
                    }
                    buffer.delete(0, buffer.length());
                } else {
                    output.append(ch);
                }
            } else {
                startWhiteSpace = false;
                output.append(ch);
            }
        }
        return new TrimmedInput(output.toString(), noOfSpacesRemoved);
    } else {
        return null;
    }
}

From source file:eagle.service.security.hdfs.resolver.HDFSCommandResolver.java

@Override
public void validateRequest(GenericAttributeResolveRequest request) throws BadAttributeResolveRequestException {
    String query = request.getQuery();
    boolean matched = Pattern.matches("[a-zA-Z]+", query);
    if (query == null || !matched) {
        throw new BadAttributeResolveRequestException(HDFS_CMD_RESOLVE_FORMAT_HINT);
    }// w  ww  . ja  v a  2  s  . c  o  m
}

From source file:hudson.plugins.validating_string_parameter.ValidatingStringParameterValidator.java

/**
 * Called to validate the passed user entered value against the configured regular expression.
 *//*from w  ww  .  j a v  a  2 s.co  m*/
public FormValidation doValidate(String regex, final String failedValidationMessage, final String value) {

    FormValidation validation = FormValidation.ok();

    if (StringUtils.isNotBlank(value)) {
        if (value.contains("$")) {
            // since this is used to disable projects, be conservative
            //            LOGGER.fine("Location could be expanded on build '" + build
            //                  + "' parameters values:");
        } else {
            if (!Pattern.matches(regex, value)) {
                try {
                    return failedValidationMessage == null || "".equals(failedValidationMessage)
                            ? FormValidation.error("Value entered does not match regular expression: " + regex)
                            : FormValidation.error(failedValidationMessage);

                } catch (PatternSyntaxException pse) {
                    validation = FormValidation
                            .error("Invalid regular expression [" + regex + "]: " + pse.getDescription());
                }
            }
            //   validation = FormValidation.error(Messages
            //      .SiteMonitor_Error_PrefixOfURL());

        }
    }

    return validation;
}

From source file:org.apache.ambari.server.security.SecurityFilter.java

private boolean isRequestAllowed(String reqUrl) {
    try {//from w  w w  .j  ava  2s  .  c  o m
        URL url = new URL(reqUrl);
        if (!"https".equals(url.getProtocol())) {
            LOG.warn(String.format("Request %s is not using HTTPS", reqUrl));
            return false;
        }

        if (Pattern.matches("/cert/ca(/?)", url.getPath())) {
            return true;
        }

        if (Pattern.matches("/connection_info", url.getPath())) {
            return true;
        }

        if (Pattern.matches("/certs/[^/0-9][^/]*", url.getPath())) {
            return true;
        }

        if (Pattern.matches("/resources/.*", url.getPath())) {
            return true;
        }

    } catch (Exception e) {
        LOG.warn("Exception while validating if request is secure " + e.toString());
    }
    LOG.warn("Request " + reqUrl + " doesn't match any pattern.");
    return false;
}

From source file:com.predic8.membrane.core.rules.SwaggerProxyKey.java

private boolean pathTemplateMatch(String calledURI, String specName) {
    final String IDENTIFIER = "[-_a-zA-Z0-9]+";
    specName = specName.replaceAll("\\{" + IDENTIFIER + "\\}", IDENTIFIER);
    String spec = swagger.getBasePath() + specName;
    return Pattern.matches(spec, calledURI);
}

From source file:org.apache.ftpserver.clienttests.SiteTest.java

public void testSiteWho() throws Exception {
    client.login(ADMIN_USERNAME, ADMIN_PASSWORD);

    client.sendCommand("SITE WHO");
    String[] siteReplies = client.getReplyString().split("\r\n");

    assertEquals("200-", siteReplies[0]);
    String pattern = "200 admin           127.0.0.1       " + TIMESTAMP_PATTERN + " " + TIMESTAMP_PATTERN + " ";

    assertTrue(Pattern.matches(pattern, siteReplies[1]));
}

From source file:net.spfbl.whois.Owner.java

/**
 * Verifica se a expresso  um CPNJ ou CPF.
 * @param id a identificao a ser verificada.
 * @return verdadeiro se a expresso  um CPNJ ou CPF.
 *//*from w  w w . j  a v  a2 s.  com*/
public static boolean isOwnerID(String id) {
    return Pattern.matches("^([0-9]{3}\\.[0-9]{3}\\.[0-9]{3}-[0-9]{2})"
            + "|([0-9]{2,3}\\.[0-9]{3}\\.[0-9]{3}/[0-9]{4}-[0-9]{2})$", id);
}

From source file:com.baidu.rigel.biplatform.ac.util.PlaceHolderUtils.java

/**
 * ?????value ???????//from   w  w w .  j a v  a2s  .  com
 * 
 * @param source ?
 * @param placeHolder ???KEY???? url  ${url}
 * @param value ????null
 * @return ???
 * @throws IllegalArgumentException ???
 */
public static String replacePlaceHolderWithValue(String source, String placeHolder, String value) {
    if (StringUtils.isBlank(source) || StringUtils.isBlank(placeHolder)) {
        throw new IllegalArgumentException("params error, source : " + source + " placeHolder:" + placeHolder);
    }
    String oldKey = placeHolder;
    if (!Pattern.matches("^\\$\\{[^\\}]+\\}$", placeHolder)) {
        oldKey = "${" + oldKey + "}";
    }

    return source.replace(oldKey, value);

}

From source file:org.apache.eagle.service.security.hdfs.resolver.MAPRFSCommandResolver.java

@Override
public void validateRequest(GenericAttributeResolveRequest request) throws BadAttributeResolveRequestException {
    String query = request.getQuery();
    boolean matched = Pattern.matches("[a-zA-Z]+", query);
    if (query == null || !matched) {
        throw new BadAttributeResolveRequestException(MAPRFS_CMD_RESOLVE_FORMAT_HINT);
    }//  w w w. j a  v a2s . c  o  m
}

From source file:org.exoplatform.utils.ExoUtils.java

/**
 * Verifies that an account name contains allowed characters only.
 * // w  ww .  ja  va2 s  .c o  m
 * @param serverName the server name to verify
 * @return true if only allowed characters are found, false otherwise.
 */
public static boolean isServerNameValid(String serverName) {
    return (serverName == null) ? false
            : Pattern.matches(ExoConstants.ALLOWED_ACCOUNT_NAME_CHARSET, serverName);
}