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:br.com.nordestefomento.jrimum.vallia.digitoverificador.BoletoLinhaDigitavelDV.java

/**
 * @see br.com.nordestefomento.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String)
 * @since 0.2//from w  w w  .  j a  va  2s.  co m
 */
@Override
public int calcule(String numero) throws IllegalArgumentException {

    int dv = 0;
    int resto = 0;

    if (StringUtils.isNotBlank(numero) && Pattern.matches(REGEX_CAMPO, numero)) {

        numero = StringUtils.replaceChars(numero, ".", "");

        resto = modulo10.calcule(numero);

        if (resto != 0)
            dv = modulo10.valor() - resto;
    } else
        throw new IllegalArgumentException("O campo [ " + numero
                + " ] da linha digitvel deve conter apenas nmeros com 9 ou 10 dgitos !");

    return dv;
}

From source file:org.apache.camel.dataformat.csv.CsvRouteTest.java

@Test
public void testMultipleMessages() throws Exception {
    MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:resultMulti", MockEndpoint.class);
    resultEndpoint.expectedMessageCount(2);
    Map<String, Object> body1 = new HashMap<String, Object>();
    body1.put("foo", "abc");
    body1.put("bar", 123);

    Map<String, Object> body2 = new HashMap<String, Object>();
    body2.put("foo", "def");
    body2.put("bar", 456);
    body2.put("baz", 789);

    template.sendBody("direct:startMulti", body1);
    template.sendBody("direct:startMulti", body2);

    resultEndpoint.assertIsSatisfied();/*from  ww  w  . j av  a 2s  .c o m*/
    List<Exchange> list = resultEndpoint.getReceivedExchanges();
    Message in1 = list.get(0).getIn();
    String text1 = in1.getBody(String.class);

    log.debug("Received " + text1);
    assertTrue("First CSV body has wrong value", Pattern.matches("(abc,123)|(123,abc)", text1.trim()));

    Message in2 = list.get(1).getIn();
    String text2 = in2.getBody(String.class);

    log.debug("Received " + text2);

    // fields should keep the same order from one call to the other
    if (text1.trim().equals("abc,123")) {
        assertEquals("Second CSV body has wrong value", "def,456,789", text2.trim());
    } else {
        assertEquals("Second CSV body has wrong value", "456,def,789", text2.trim());
    }
}

From source file:com.linuxbox.enkive.filter.EnkiveFilter.java

private boolean filterString(String value) {
    boolean matched = false;
    switch (filterComparator) {
    case FilterComparator.MATCHES:
        if (value.trim().equals(filterValue)) {
            matched = true;/*from w  w  w  .ja v  a2s  .c om*/
        }
        break;
    case FilterComparator.DOES_NOT_MATCH:
        if (!value.trim().equals(filterValue))
            matched = true;
        break;
    case FilterComparator.CONTAINS:
        if (Pattern.matches(filterValue, value))
            ;
        matched = true;
        break;
    case FilterComparator.DOES_NOT_CONTAIN:
        if (!Pattern.matches(filterValue, value))
            ;
        matched = true;
        break;
    }
    return matched;
}

From source file:br.com.nordestefomento.jrimum.vallia.digitoverificador.CPFDV.java

/**
 * @see br.com.nordestefomento.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String)
 * @since 0.2/*from   w w w  .  j a v a  2 s.co m*/
 */
@Override
public int calcule(String numero) throws IllegalArgumentException {

    int dv1 = 0;
    int dv2 = 0;
    boolean isFormatoValido = false;

    validacao: {

        if (StringUtils.isNotBlank(numero)) {

            isFormatoValido = (Pattern.matches(REGEX_CPF_DV, numero)
                    || Pattern.matches(REGEX_CPF_DV_FORMATTED, numero));

            if (isFormatoValido) {

                numero = StringUtils.replaceChars(numero, ".", "");

                dv1 = calcule(numero, 10);
                dv2 = calcule(numero + dv1, 11);

                break validacao;
            }
        }

        throw new IllegalArgumentException("O CPF [ " + numero
                + " ] deve conter apenas nmeros, sendo eles no formato ###.###.### ou ######### !");

    }

    return Integer.parseInt(dv1 + "" + dv2);

}

From source file:com.mindcognition.mindraider.ui.swing.concept.annotation.transformer.RichTextToHtmlTransformer.java

/**
 * Content based colorization of the annotation - mainly todos:
 * <ul>//from  w w  w.j  ava  2s .  co m
 *  <li>o normal
 *  <li>x done (gray)
 *  <li>! important (red)
 *  <li>? question (blue)
 * <ul>
 * 
 * @param annotation
 * @return
 */
private String htmlColorizeToDoLine(String line) {
    if (line == null) {
        return null;
    } else {
        int idx;
        String prefix;

        final int EXTRA_INDENTATION = 1; // for twiki it is 3
        if (Pattern.matches("^[ ]+o .*", line)) {
            idx = line.indexOf('o');
            line = line.substring(idx + 1);
            prefix = "";
            for (int i = 0; i < idx * EXTRA_INDENTATION; i++) {
                prefix += " ";
            }
            line = prefix + "o" + line;
        } else {
            if (Pattern.matches("^[ ]+! .*", line)) {
                prefix = "";
                while (line.startsWith(" ")) {
                    prefix += " ";
                    line = line.substring(1);
                }
                line = prefix + "! <b><font color='#dd6060'>" + line.substring(1) + "</font></b>";
            } else {
                if (Pattern.matches("^[ ]+x .*", line)) {
                    idx = line.indexOf('x');
                    line = line.substring(idx + 1);
                    prefix = "";
                    for (int i = 0; i < idx * EXTRA_INDENTATION; i++) {
                        prefix += " ";
                    }
                    line = prefix + "x <i><font color='gray'>" + line + "</font></i>";
                } else {
                    if (Pattern.matches("^[ ]+\\? .*", line)) {
                        idx = line.indexOf('?');
                        line = line.substring(idx + 1);
                        prefix = "";
                        for (int i = 0; i < idx * EXTRA_INDENTATION; i++) {
                            prefix += " ";
                        }
                        line = prefix + "? <b><font color='blue'>" + line + "</font></b>";
                    }
                }
            }
        }

        return line + "\n";
    }
}

From source file:com.norconex.importer.handler.tagger.impl.KeepOnlyTagger.java

private boolean mustKeep(String fieldToMatch) {
    // Check with exact field names
    for (String field : fields) {
        if (field.trim().equalsIgnoreCase(fieldToMatch.trim())) {
            return true;
        }// w  w  w.  j  a va2s  .c  o m
    }

    // Check with regex
    if (StringUtils.isNotBlank(fieldsRegex) && Pattern.matches(fieldsRegex, fieldToMatch)) {
        return true;
    }
    return false;
}

From source file:com.microsoft.azure.management.compute.VirtualMachineSizeOperationsImpl.java

/**
* Lists virtual-machine-sizes available in a location for a subscription.
*
* @param location Required. The location upon which virtual-machine-sizes
* is queried./*from w ww . ja v a 2 s .c  o m*/
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The List Virtual Machine operation response.
*/
@Override
public VirtualMachineSizeListResponse list(String location)
        throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (location == null) {
        throw new NullPointerException("location");
    }
    if (location != null && location.length() > 1000) {
        throw new IllegalArgumentException("location");
    }
    if (Pattern.matches("^[-\\w\\._]+$", location) == false) {
        throw new IllegalArgumentException("location");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("location", location);
        CloudTracing.enter(invocationId, this, "listAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/providers/";
    url = url + "Microsoft.Compute";
    url = url + "/locations/";
    url = url + URLEncoder.encode(location, "UTF-8");
    url = url + "/vmSizes";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-06-15");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        VirtualMachineSizeListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualMachineSizeListResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                JsonNode valueArray = responseDoc.get("value");
                if (valueArray != null && valueArray instanceof NullNode == false) {
                    for (JsonNode valueValue : ((ArrayNode) valueArray)) {
                        VirtualMachineSize virtualMachineSizeInstance = new VirtualMachineSize();
                        result.getVirtualMachineSizes().add(virtualMachineSizeInstance);

                        JsonNode nameValue = valueValue.get("name");
                        if (nameValue != null && nameValue instanceof NullNode == false) {
                            String nameInstance;
                            nameInstance = nameValue.getTextValue();
                            virtualMachineSizeInstance.setName(nameInstance);
                        }

                        JsonNode numberOfCoresValue = valueValue.get("numberOfCores");
                        if (numberOfCoresValue != null && numberOfCoresValue instanceof NullNode == false) {
                            int numberOfCoresInstance;
                            numberOfCoresInstance = numberOfCoresValue.getIntValue();
                            virtualMachineSizeInstance.setNumberOfCores(numberOfCoresInstance);
                        }

                        JsonNode osDiskSizeInMBValue = valueValue.get("osDiskSizeInMB");
                        if (osDiskSizeInMBValue != null && osDiskSizeInMBValue instanceof NullNode == false) {
                            int osDiskSizeInMBInstance;
                            osDiskSizeInMBInstance = osDiskSizeInMBValue.getIntValue();
                            virtualMachineSizeInstance.setOSDiskSizeInMB(osDiskSizeInMBInstance);
                        }

                        JsonNode resourceDiskSizeInMBValue = valueValue.get("resourceDiskSizeInMB");
                        if (resourceDiskSizeInMBValue != null
                                && resourceDiskSizeInMBValue instanceof NullNode == false) {
                            int resourceDiskSizeInMBInstance;
                            resourceDiskSizeInMBInstance = resourceDiskSizeInMBValue.getIntValue();
                            virtualMachineSizeInstance.setResourceDiskSizeInMB(resourceDiskSizeInMBInstance);
                        }

                        JsonNode memoryInMBValue = valueValue.get("memoryInMB");
                        if (memoryInMBValue != null && memoryInMBValue instanceof NullNode == false) {
                            int memoryInMBInstance;
                            memoryInMBInstance = memoryInMBValue.getIntValue();
                            virtualMachineSizeInstance.setMemoryInMB(memoryInMBInstance);
                        }

                        JsonNode maxDataDiskCountValue = valueValue.get("maxDataDiskCount");
                        if (maxDataDiskCountValue != null
                                && maxDataDiskCountValue instanceof NullNode == false) {
                            int maxDataDiskCountInstance;
                            maxDataDiskCountInstance = maxDataDiskCountValue.getIntValue();
                            virtualMachineSizeInstance.setMaxDataDiskCount(maxDataDiskCountInstance);
                        }
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

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

/**
 * ?//  w ww .j  a  va 2s.c  o  m
 *
 * @param str
 * @return
 */
public static boolean isNumber(String str) {
    if (StringUtils.isNotBlank(str)) {
        String regex = "^[1-9]\\d*$";
        return Pattern.matches(regex, str);
    }
    return false;
}

From source file:org.iish.visualmets.services.ImageTransformation.java

public BufferedImage CropImage(BufferedImage img, String crop) {
    BufferedImage clipped = null;
    boolean coordinates_okay = false;

    if (!crop.trim().equals("")) {
        coordinates_okay = true;/*from   w w w . j ava  2 s. com*/

        int[] coordinates = { 0, 0, img.getWidth(), img.getHeight() };

        // split crop value in parts
        String[] crop_coordinates = crop.split(",");

        // if still okay, check if each part is a integer
        if (coordinates_okay) {
            for (int i = 0; i < crop_coordinates.length && i < 4; i++) {
                if (!crop_coordinates[i].trim().equals("")) {
                    if (!Pattern.matches("^-?\\d*$", crop_coordinates[i].trim())) {
                        coordinates_okay = false;
                    } else {
                        coordinates[i] = parseInt(crop_coordinates[i].trim());
                    }
                }
            }
        }

        // als coordinaten negatief, dan vanuit gaan dat het van de 'andere' kant is
        if (coordinates_okay) {
            if (coordinates[0] < 0) {
                coordinates[0] = img.getWidth() + coordinates[0];
            }

            if (coordinates[1] < 0) {
                coordinates[1] = img.getHeight() + coordinates[1];
            }

            if (coordinates[2] < 0) {
                coordinates[2] = img.getWidth() + coordinates[2];
            }

            if (coordinates[3] < 0) {
                coordinates[3] = img.getHeight() + coordinates[3];
            }
        }

        // alle coordinaten moeten op dit moment positieve getallen binnen de image grootte/breedte zijn
        if (coordinates_okay) {
            if (coordinates[0] > img.getWidth() || coordinates[0] < 0) {
                coordinates_okay = false;
            }

            if (coordinates[1] > img.getHeight() || coordinates[1] < 0) {
                coordinates_okay = false;
            }

            if (coordinates[2] > img.getWidth() || coordinates[2] < 0) {
                coordinates_okay = false;
            }

            if (coordinates[3] > img.getHeight() || coordinates[3] < 0) {
                coordinates_okay = false;
            }
        }

        // controleer of de linker/boven waarde kleiner is dan de rechter/onder coordinaat
        if (coordinates_okay) {
            if (coordinates[0] >= coordinates[2]) {
                coordinates_okay = false;
            }
            if (coordinates[1] >= coordinates[3]) {
                coordinates_okay = false;
            }
        }

        if (coordinates_okay) {
            // if still okay, then get cropped image
            try {
                int w = coordinates[2] - coordinates[0];
                int h = coordinates[3] - coordinates[1];

                clipped = img.getSubimage(coordinates[0], coordinates[1], w, h);
            } catch (RasterFormatException rfe) {
                System.out.println("raster format error: " + rfe.getMessage());
                coordinates_okay = false;
            }
        }
    }

    if (!coordinates_okay) {
        clipped = img;
    }

    return clipped;
}

From source file:nl.knaw.dans.common.lang.user.PersonVO.java

public void setTelephone(String telephone) {
    if (telephone != null && !Pattern.matches(PATTERN_TELEPHONE, telephone)) {
        throw new IllegalArgumentException("Invalid syntax for telephone numbers: " + telephone);
    }/* ww w.j a v a2s . c  o  m*/
    this.telephone = telephone;
}