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.wyb.utils.util.PatternUtil.java

/**
 * ??/*from w w w .  ja  va2s . c  o m*/
 *
 * @param postCode ?
 * @return ??true?false
 */
public static boolean isPostcode(String postCode) {
    if (StringUtils.isNotBlank(postCode)) {
        String regex = "[1-9]\\d{5}";
        return Pattern.matches(regex, postCode);
    }
    return false;
}

From source file:org.apache.any23.util.StringUtils.java

/**
 * Changes string with following convention:
 * <ul>/* www. ja v a  2 s  . c o m*/
 * <li>Changes '-' -&gt; '_'
 * <li>remove space characters and make first letter word uppercase: 'some
 * string' -&gt; 'someString'
 * </ul>
 * If input string does not contains a whitespace than return unchanged.
 *
 * @param in an input string to convert to Java code convention
 * @return the correctly formatter string as per Java spec.
 */
public static String implementJavaNaming(String in) {

    in = in.trim().replaceAll("-", "_");

    // If no white chars found inside a string return uncapitalized
    if (in.trim().matches("\\S+")) {
        return WordUtils.uncapitalize(in);
    }

    in = in.toLowerCase();
    if (Pattern.matches("\\S+(\\s+\\S+)+", in)) {
        String[] words = in.split("\\s", 2);
        in = words[0] + WordUtils.capitalize(words[1]).replaceAll("\\s", "");
    }

    return in;
}

From source file:com.revolsys.ui.html.domain.PhoneNumber.java

public static boolean isValid(final String phoneNumber) {
    final String number = normalize(phoneNumber);
    return Pattern.matches("^\\d+$", number);
}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean checkValidationForContentTreeItemAnnotation(Field field, Object currSceneController,
        EditorPanel.EDITOR_BUTTON_TYPE type) {
    boolean contentIsCorrect = false;
    Annotations.ContentTreeItem annotation = field.getAnnotation(Annotations.ContentTreeItem.class);
    Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController);
    String content = (String) typeAndContent[1];

    if (content.length() != Integer.parseInt(annotation.valueForLength())) {
        changeNodeTitleLabelVisual((Node) typeAndContent[0],
                annotation.explainForLength() + annotation.valueForLength());
    } else if (!Pattern.matches(annotation.valueForSyntax(), content)) {
        changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForSyntax());
    } else {//from w ww  .  j a va  2 s .c o m
        EditorPanelable newPanelableObject = (EditorPanelable) getInvokedClassMethod(
                currSceneController.getClass(), "getNewEditorPanelable", null, currSceneController);
        Object contr = getInvokedClassMethod(currSceneController.getClass(), "getOwnerController", null,
                currSceneController);
        // already exist this item for this code:
        if ((Boolean) getInvokedClassMethod(contr.getClass(), "accountAlreadyExistForCode",
                new Class[] { EditorPanelable.class, EditorPanel.EDITOR_BUTTON_TYPE.class }, contr,
                newPanelableObject, type)) {
            changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForExists());
        }
        // item has not a parent:
        else if (!(Boolean) getInvokedClassMethod(contr.getClass(), "accountHasParent",
                new Class[] { String.class }, contr, content)) {
            changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForHasNotParent());
        } else {
            changeNodeTitleLabelVisual((Node) typeAndContent[0], "");
            contentIsCorrect = true;
        }
    }
    return contentIsCorrect;
}

From source file:com.fastandroid.lib.http.AsyncHttpClient.BinaryHttpResponseHandler.java

@Override
protected void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody);
        return;//  w  w  w  .j  av a 2 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) {
        // Content-Type not in allowed list, ABORT!
        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, (byte[]) null);
    }

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

From source file:com.kixeye.chassis.transport.websocket.WebSocketSession.java

/**
 * Returns true if there is a property with the given name and the value matches using {@link Pattern}.matches().
 * //from w w  w. j a v  a 2  s. co m
 * @param name
 * @param regex
 * @return
 */
public boolean matchesProperty(String name, String regex) {
    String propValue = properties.get(name);

    return Pattern.matches(regex, propValue);
}

From source file:hydrograph.ui.graph.editor.RenameJobParticipant.java

@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    final HashMap<IFile, RenameResourceChange> changes = new HashMap<IFile, RenameResourceChange>();
    final String newName = ResourceChangeUtil.removeExtension(getArguments().getNewName());

    if (modifiedResource.getParent() != null) {
        if (!StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(),
                CustomMessages.ProjectSupport_JOBS)) {
            List<IResource> memberList = new ArrayList<IResource>(modifiedResource.getProject()
                    .getFolder(modifiedResource.getParent().getName()).members().length);
            ResourceChangeUtil.addMembersToList(memberList,
                    modifiedResource.getProject().getFolder(modifiedResource.getParent().getName()));
            final String fileName = ResourceChangeUtil.removeExtension(modifiedResource.getName());
            for (IResource resource : memberList) {
                if (Pattern.matches(fileName + Constants.EXTENSION, resource.getName())) {
                    if ((StringUtils.equalsIgnoreCase(Messages.XML_EXT, resource.getFileExtension())
                            || StringUtils.equalsIgnoreCase(Messages.JOB_EXT, resource.getFileExtension()))
                            && !(StringUtils.equalsIgnoreCase(modifiedResource.getName(),
                                    resource.getName()))) {
                        getRenameChanges(changes, newName, resource);
                    }/*from w w w . jav  a  2 s .  c  om*/
                }
            }
        } else if (StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(),
                CustomMessages.ProjectSupport_JOBS)
                || StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(),
                        CustomMessages.ProjectSupport_PARAM)) {
            List<IResource> memberList = new ArrayList<IResource>(modifiedResource.getProject()
                    .getFolder(CustomMessages.ProjectSupport_PARAM).members().length
                    + modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_JOBS)
                            .members().length);
            ResourceChangeUtil.addMembersToList(memberList,
                    modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_JOBS));
            ResourceChangeUtil.addMembersToList(memberList,
                    modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_PARAM));
            final String fileName = ResourceChangeUtil.removeExtension(modifiedResource.getName());
            for (IResource resource : memberList) {
                if (Pattern.matches(fileName + Constants.EXTENSION, resource.getName())) {
                    if ((StringUtils.equalsIgnoreCase(Messages.XML_EXT, resource.getFileExtension())
                            || StringUtils.equalsIgnoreCase(Messages.PROPERTIES_EXT,
                                    resource.getFileExtension())
                            || StringUtils.equalsIgnoreCase(Messages.JOB_EXT, resource.getFileExtension()))
                            && !(StringUtils.equalsIgnoreCase(modifiedResource.getName(),
                                    resource.getName()))) {
                        getRenameChanges(changes, newName, resource);
                    }
                    ;
                }
            }
        }
    }

    if (changes.isEmpty()) {
        return null;
    }

    CompositeChange result = new CompositeChange("Rename Job Related Files");
    for (Iterator<RenameResourceChange> iter = changes.values().iterator(); iter.hasNext();) {
        result.add((Change) iter.next());
    }
    return result;
}

From source file:com.alading.library.util.http.BinaryHttpResponseHandler.java

@Override
protected void sendResponseMessage(HttpResponse response, String requset) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), responseBody, requset);
        return;//  w  ww  .  ja  va  2  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) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
                responseBody, requset);
        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, (byte[]) null, requset);
    }

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

From source file:com.strandls.alchemy.rest.client.stubgenerator.RestProxyGenerator.java

/**
 * @return the rest webservice classes to process.
 * @throws MalformedURLException// w  w w  .  j a  va 2 s  . c om
 */
private Set<Class<?>> findServiceClasses() {
    final List<Object> params = new ArrayList<Object>();
    final ClassLoader loader = getClass().getClassLoader();
    if (loader instanceof AntClassLoader) {
        final String[] path = ((AntClassLoader) loader).getClasspath()
                .split(System.getProperty("path.separator"));
        for (final String string : path) {
            try {
                params.add(new URL(string));
            } catch (final MalformedURLException e) {
                try {
                    params.add(new URL("file://" + string));
                } catch (final MalformedURLException e1) {
                    throw new RuntimeException(e1);
                }
            }
        }

    }

    final Reflections reflections = new Reflections(params.toArray(new Object[0]));
    final Set<Class<?>> allRestServices = reflections.getTypesAnnotatedWith(Path.class);
    log("Locating service classes", Project.MSG_ERR);

    final Set<Class<?>> filtered = Sets.filter(allRestServices, new Predicate<Class<?>>() {
        @Override
        public boolean apply(final Class<?> input) {
            return doesMatch(input, includes) && !doesMatch(input, excludes);
        }

        /**
         * Indicates if the input class matches any one of the comma
         * separated regex patterns.
         *
         * <code>null</code> or empty pattern implies no match.
         *
         * @param input
         *            the input class.
         * @param patterns
         *            comma separated list of patterns.
         *
         * @return <code>true</code> if any one of the pattern matches the
         *         canonical name of the class.
         */
        private boolean doesMatch(final Class<?> input, final String patterns) {
            boolean matches = false;
            if (patterns != null) {
                for (final String include : patterns.split("\\s*,\\s*")) {
                    matches |= Pattern.matches(include, input.getCanonicalName());
                }
            }
            return matches;
        }
    });

    for (final Class<?> klass : filtered) {
        log("Will process class: " + klass.getCanonicalName(), Project.MSG_ERR);
    }

    return filtered;
}

From source file:com.fanniemae.ezpie.common.StringUtilities.java

public static boolean isBigDecimal(String value) {
    if (isNullOrEmpty(value))
        return false;
    value = value.trim();//from   w w  w .j av  a2 s . c om
    if (value.indexOf('.') == -1)
        return false;
    return Pattern.matches(DOUBLE_REGEX, value);
}