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.coinblesk.server.controller.ForexController.java

/**
 * Returns up to date exchangerate BTC/CHF
 *
 * @return CustomResponseObject with exchangeRate BTC/CHF as a String
 *///from  w  w  w.  j a v  a2  s.c  om
@RequestMapping(value = "/rate/{from}-{to}", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
@ApiVersion({ "v2" })
@ResponseBody
public ResponseEntity<ExchangeRateTO> forexExchangeRate(@PathVariable(value = "from") String from,
        @PathVariable(value = "to") String to) {

    LOG.debug("{exchange-rate} - Received exchange rate request for currency {}/{}", from, to);
    ExchangeRateTO output = new ExchangeRateTO();
    try {
        if (!Pattern.matches("[A-Z]{3}", from) || !Pattern.matches("[A-Z]{3}", to)) {
            output.type(SERVER_ERROR).message("unknown currency symbol");
            return new ResponseEntity<>(output, BAD_REQUEST);
        }
        BigDecimal exchangeRate = forexExchangeRateService.getExchangeRate(from, to);
        output.name(from + to);
        output.rate(exchangeRate.toString());
        output.setSuccess();

        LOG.debug("{exchange-rate} - {}, rate: {}", output.name(), output.rate());
        return new ResponseEntity<>(output, OK);

    } catch (Exception e) {
        LOG.error("{exchange-rate} - SERVER_ERROR - exception: ", e);
        output.type(SERVER_ERROR);
        output.message(e.getMessage());
        return new ResponseEntity<>(output, BAD_REQUEST);
    }
}

From source file:com.anite.antelope.validation.RegexMaskStringValidator.java

public boolean doValidate(ParameterParser params, String key, ValidationResults validationData)
        throws ReviewValidationException {
    boolean valid = true;
    String[] values = params.getStrings(key);
    if (values == null) {
        return valid;
    }//  ww w . j a v a2 s. c om

    String regexMask = (String) args.get("regexMask");
    String invalidFormatMessage = (String) args.get("invalidFormatMessage");

    for (int i = 0; i < values.length; i++) {
        if (!Pattern.matches(regexMask, values[i])) {
            valid = false;
            validationData.addMessage(key, invalidFormatMessage);
        }
    }
    log.debug("Called validate() : returning :" + (new Boolean(valid)).toString());
    return valid;
}

From source file:com.nextep.datadesigner.sqlgen.impl.SynchronizationFilter.java

@Override
public boolean match(ITypedObject object) {
    if (object == null)
        return false;
    if (object.getType() == getType() || getType() == null) {
        if (object instanceof INamedObject) {
            final INamedObject named = (INamedObject) object;
            try {
                return Pattern.matches(getName(), named.getName());
            } catch (RuntimeException e) {
                LOGGER.error("Unable to compile synchronization filter '" + getName() + "': " + e.getMessage(),
                        e);/* w ww .j a v  a  2 s . com*/
            }
        }
    }
    return false;
}

From source file:com.wyb.utils.util.PatternUtil.java

/**
 * ????/*from  ww  w  .  ja  v a2s. c  o m*/
 *
 * @param tellPhone ?????? + ?? + ???+8602085588447
 *                  <p><b> ? </b>????? 0  9 ??
 *                  ??</p>
 *                  <p><b>??</b>?? 0  9 ??
 *                  ???</p>
 *                  <p><b>???</b>? 0  9  </p>
 * @return ??true?false
 */
public static boolean isTellPhone(String tellPhone) {
    if (StringUtils.isBlank(tellPhone)) {
        return false;
    }
    String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$";
    return Pattern.matches(regex, tellPhone);
}

From source file:com.galenframework.actions.GalenActionCheckArguments.java

private static Dimension convertScreenSize(String text) {
    if (text == null) {
        return null;
    }//from  w w w  .  ja  v a2 s.com

    if (Pattern.matches("[0-9]+x[0-9]+", text)) {
        String[] values = text.split("x");
        if (values.length == 2) {
            return new Dimension(parseInt(values[0]), parseInt(values[1]));
        }
    }

    throw new IllegalArgumentException("Incorrect size: " + text);
}

From source file:com.evolveum.midpoint.prism.match.ExchangeEmailAddressesMatchingRule.java

@Override
public boolean matchRegex(String a, String regex) {
    if (a == null) {
        return false;
    }// w  w w .ja  v  a 2  s  . c o m
    return Pattern.matches(regex, a); // we ignore case-insensitiveness of the email address
}

From source file:core.plugin.mybatis.PageInterceptor.java

@Override
public Object intercept(Invocation inv) throws Throwable {
    // prepare?Connection
    Connection connection = (Connection) inv.getArgs()[0];
    String dbType = connection.getMetaData().getDatabaseProductName();
    L.debug(dbType);//ww  w .  j  a  va  2s.  co m
    Dialect dialect = null;
    if (StringUtils.equalsIgnoreCase("ORACLE", dbType)) {
        dialect = new OracleDialect();
    } else if (StringUtils.equalsIgnoreCase("H2", dbType)) {
        dialect = new H2Dialect();
    } else {
        throw new AppRuntimeException("A404: Not Support ['" + dbType + "'] Pagination Yet!");
    }

    StatementHandler target = (StatementHandler) inv.getTarget();
    BoundSql boundSql = target.getBoundSql();
    String sql = boundSql.getSql();
    if (StringUtils.isBlank(sql)) {
        return inv.proceed();
    }
    // ?select??
    if (sql.matches(SQL_SELECT_REGEX) && !Pattern.matches(SQL_COUNT_REGEX, sql)) {
        Object obj = FieldUtils.readField(target, "delegate", true);
        // ??? RowBounds 
        RowBounds rowBounds = (RowBounds) FieldUtils.readField(obj, "rowBounds", true);
        // ??SQL
        if (rowBounds != null && rowBounds != RowBounds.DEFAULT) {
            FieldUtils.writeField(boundSql, "sql", dialect.getSqlWithPagination(sql, rowBounds), true);
            // ???(?)
            FieldUtils.writeField(rowBounds, "offset", RowBounds.NO_ROW_OFFSET, true);
            FieldUtils.writeField(rowBounds, "limit", RowBounds.NO_ROW_LIMIT, true);
        }
    }
    return inv.proceed();
}

From source file:fr.inria.oak.paxquery.pact.operations.RecordPredicateEvaluation.java

private static boolean evaluateSimplePredicate(NestedMetadata inputRecordSignature, Record record,
        SimplePredicate simplePred) {//ww w .  j av a  2  s . co m
    try {
        String numericPattern = "^-?\\d+([,\\.]\\d+)?([eE]-?\\d+)?$";
        boolean isValue1Number, isValue2Number;

        double value1, value2;

        //We are evaluating a predicate over two columns!
        if (simplePred.getStringConstant() == null && simplePred.getDoubleConstant() == -1) {
            switch (simplePred.getPredCode()) {
            case PREDICATE_EQUAL:
                isValue1Number = Pattern.matches(numericPattern,
                        record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                isValue2Number = Pattern.matches(numericPattern,
                        record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                if (isValue1Number && isValue2Number) {
                    //both columns contain numbers
                    value1 = Double.parseDouble(
                            record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                    if (simplePred.getOperation1() != null)
                        value1 = simplePred.getOperation1().calculate(value1);
                    value2 = Double.parseDouble(
                            record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                    if (simplePred.getOperation2() != null)
                        value2 = simplePred.getOperation2().calculate(value2);
                    return value1 == value2;
                } else if (!isValue1Number && !isValue2Number) //both columns contain non-number strings
                    return record
                            .getField(simplePred.getColumn1(),
                                    MetadataTypesMapping.getValueClass(
                                            inputRecordSignature.getType(simplePred.getColumn1())))
                            .equals(record.getField(simplePred.getColumn2(), MetadataTypesMapping
                                    .getValueClass(inputRecordSignature.getType(simplePred.getColumn2()))));
                else //a number and a non-number, result must be false
                    return false;
            case PREDICATE_NOTEQUAL:
                isValue1Number = Pattern.matches(numericPattern,
                        record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                isValue2Number = Pattern.matches(numericPattern,
                        record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                if (isValue1Number && isValue2Number) {
                    //both columns contain numbers
                    value1 = Double.parseDouble(
                            record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                    if (simplePred.getOperation1() != null)
                        value1 = simplePred.getOperation1().calculate(value1);
                    value2 = Double.parseDouble(
                            record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                    if (simplePred.getOperation2() != null)
                        value2 = simplePred.getOperation2().calculate(value2);
                    return value1 != value2;
                } else //at least one column contains a non-number, test for non-equality
                    return !record
                            .getField(simplePred.getColumn1(),
                                    MetadataTypesMapping.getValueClass(
                                            inputRecordSignature.getType(simplePred.getColumn1())))
                            .equals(record.getField(simplePred.getColumn2(), MetadataTypesMapping
                                    .getValueClass(inputRecordSignature.getType(simplePred.getColumn2()))));
            case PREDICATE_SMALLEROREQUALTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                value2 = Double
                        .parseDouble(record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                if (simplePred.getOperation2() != null)
                    value2 = simplePred.getOperation2().calculate(value2);
                return value1 <= value2;
            case PREDICATE_SMALLERTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                value2 = Double
                        .parseDouble(record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                if (simplePred.getOperation2() != null)
                    value2 = simplePred.getOperation2().calculate(value2);
                return value1 < value2;
            case PREDICATE_GREATEROREQUALTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                value2 = Double
                        .parseDouble(record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                if (simplePred.getOperation2() != null)
                    value2 = simplePred.getOperation2().calculate(value2);
                return value1 >= value2;
            case PREDICATE_GREATERTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                value2 = Double
                        .parseDouble(record.getField(simplePred.getColumn2(), StringValue.class).getValue());
                if (simplePred.getOperation2() != null)
                    value2 = simplePred.getOperation2().calculate(value2);
                return value1 > value2;
            default:
                throw new PAXQueryExecutionException(
                        "Predicate " + simplePred.toString() + " not implemented yet!");
            }
        } else if (simplePred.getDoubleConstant() != -1) {
            //We are evaluating a predicate over a column and a double constant
            switch (simplePred.getPredCode()) {
            case PREDICATE_EQUAL:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                return value1 == simplePred.getDoubleConstant();
            case PREDICATE_NOTEQUAL:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                return value1 != simplePred.getDoubleConstant();
            case PREDICATE_SMALLEROREQUALTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                return value1 <= simplePred.getDoubleConstant();
            case PREDICATE_SMALLERTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                return value1 < simplePred.getDoubleConstant();
            case PREDICATE_GREATEROREQUALTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                return value1 >= simplePred.getDoubleConstant();
            case PREDICATE_GREATERTHAN:
                value1 = Double
                        .parseDouble(record.getField(simplePred.getColumn1(), StringValue.class).getValue());
                if (simplePred.getOperation1() != null)
                    value1 = simplePred.getOperation1().calculate(value1);
                return value1 > simplePred.getDoubleConstant();
            default:
                throw new PAXQueryExecutionException(
                        "Predicate " + simplePred.toString() + " not implemented yet!");
            }
        }

        //We are evaluating a predicate over a column and a string constant
        switch (simplePred.getPredCode()) {
        case PREDICATE_EQUAL:
            if (simplePred.getStringConstant().startsWith("~")) {
                Pattern p = Pattern.compile(
                        "(^|\\s+|[^a-zA-Z0-9]+)" + simplePred.getStringConstant().substring(1,
                                simplePred.getStringConstant().length()) + "($|\\s+|[^a-zA-Z0-9]+)",
                        Pattern.MULTILINE);
                Matcher m = p.matcher(record.getField(simplePred.getColumn1(), StringValue.class));
                return m.find();
            }
            return record.getField(simplePred.getColumn1(), StringValue.class).toString()
                    .equals(simplePred.getStringConstant());
        case PREDICATE_NOTEQUAL:
            if (simplePred.getStringConstant().startsWith("~")) {
                Pattern p = Pattern.compile(
                        "(^|\\s+|[^a-zA-Z0-9]+)" + simplePred.getStringConstant().substring(1,
                                simplePred.getStringConstant().length()) + "($|\\s+|[^a-zA-Z0-9]+)",
                        Pattern.MULTILINE);
                Matcher m = p.matcher(record.getField(simplePred.getColumn1(), StringValue.class));
                return !m.find();
            }
            return !record.getField(simplePred.getColumn1(), StringValue.class).toString()
                    .equals(simplePred.getStringConstant());
        default:
            throw new PAXQueryExecutionException(
                    "Predicate " + simplePred.toString() + " not implemented yet!");
        }
    } catch (NumberFormatException nfe) {
        return false;
    }
}

From source file:cn.com.lowe.android.tools.net.response.BinaryHttpResponseHandler.java

@Override
public void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;/*from   w  ww . jav  a2 s  .  c  o  m*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody);
        return;
    }
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
        }
        responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        sendFailureMessage(e, responseBody);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.root.RegistrationValidator.java

public void validate(Object command, Errors errors) {
    RegistrationCommand registrationCommand = (RegistrationCommand) command;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "givenname", "required.field");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "required.field");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dateOfBirth", "required.field");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender", "required.field");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "required.field");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required.field");

    try {//  w w w  . j  av  a2s . c  o m
        Date d = ControllerUtils.getDateFormat().parse(registrationCommand.getDateOfBirth());
        if (d.getTime() >= System.currentTimeMillis()) {
            errors.rejectValue("dateOfBirth", "invalid.dateOfBirth");
        }
    } catch (ParseException e) {
        errors.rejectValue("dateOfBirth", "invalid.dateOfBirth");
    }

    if (!registrationCommand.getPassword().equals(registrationCommand.getPassword2())) {
        errors.rejectValue("password2", "invalid.passwordMatch");
    }
    if (!Pattern.matches("[a-zA-Z][a-zA-Z\\s]*", registrationCommand.getGivenname())) {
        errors.rejectValue("givenname", "invalid.givenname");
    }
    if (!Pattern.matches("[a-zA-Z][a-zA-Z\\s]*", registrationCommand.getSurname())) {
        errors.rejectValue("surname", "invalid.surname");
    }

    if (!Pattern.matches("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$", registrationCommand.getEmail())) {
        errors.rejectValue("email", "invalid.email");
    }

    if (personDao.usernameExists(registrationCommand.getEmail())) {
        errors.rejectValue("email", "inUse.email");
    }

    if (registrationCommand.getPassword().length() < ControllerUtils.MINIMUM_PASSWORD_LENGTH) {
        errors.rejectValue("password", "invalid.minimumPasswordLength6");
    }
}