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.btmatthews.atlas.jcr.impl.JCRTemplate.java

/**
 * Create and execute a query returning an iterator that can be used to iterate through a subset of the query results.
 *
 * @param session    The JCR session./*from  w  w w  .ja  v a2  s .  com*/
 * @param statement  The query statement.
 * @param language   The query language.
 * @param parameters Query parameters.
 * @param offset     The starting offset in the result set.
 * @param limit      The maximum number of records to return from the result set.
 * @return A {@link NodeIterator} that can be used to iterate through the subset of the query results.
 * @throws RepositoryException       Thrown by the JCR API operations if there is an error.
 * @throws RepositoryAccessException If there was an unexpected result from a JCR API operation.
 */

private NodeIterator getQueryResults(final Session session, final String statement, final String language,
        final Map<String, Object> parameters, final long offset, final long limit) throws RepositoryException {
    assert session != null;
    assert statement != null && Pattern.matches(QUERY_PATTERN, statement);
    assert language != null && Pattern.matches(LANGUAGE_PATTERN, language);
    assert offset >= 0;
    assert limit > 0;

    final Workspace workspace = session.getWorkspace();
    if (workspace == null) {
        throw new RepositoryAccessException(GET_WORKSPACE_RETURNED_NULL);
    }
    final QueryManager queryManager = workspace.getQueryManager();
    if (queryManager == null) {
        throw new RepositoryAccessException(GET_QUERY_MANAGER_RETURNED_NULL);
    }
    final Query query = queryManager.createQuery(statement, language);
    if (query == null) {
        throw new RepositoryAccessException(CREATE_QUERY_RETURNED_NULL);
    }
    query.setOffset(offset);
    query.setLimit(limit);
    if (!parameters.isEmpty()) {
        final ValueFactory valueFactory = session.getValueFactory();
        if (valueFactory == null) {
            throw new RepositoryAccessException(GET_VALUE_FACTORY_RETURNED_NULL);
        }
        for (final Map.Entry<String, Object> parameter : parameters.entrySet()) {
            bindValue(query, valueFactory, parameter.getKey(), parameter.getValue());
        }
    }
    final QueryResult queryResult = query.execute();
    if (queryResult == null) {
        throw new RepositoryAccessException(EXECUTE_RETURNED_NULL);
    }
    final NodeIterator iterator = queryResult.getNodes();
    if (iterator == null) {
        throw new RepositoryAccessException(GET_NODES_RETURNED_NULL);
    }
    return iterator;
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Reasonable check that a string might be a valid email address
 * @param email String perhaps conforming to the RFC for email addresses
 * @return True if conforms to RFC 822/*w  w  w .ja va 2s . co  m*/
 */
private boolean isValidEmailAddress(String email) {
    String regex = "^[-!#$%&'*+/0-9=?^_a-z{|}~]([+\\.]?[-!#$%&'*/0-9=?^_a-z{|}~])*@[a-z](-?[a-z0-9])*(\\.[a-z](-?[a-z0-9])*)+$";
    return Pattern.matches(regex, email.toLowerCase());
}

From source file:com.vgi.mafscaling.Rescale.java

private void recalculateNewGs() {
    try {// w w w  . j  a  v  a 2  s  .  c  o  m
        if (origVoltArray.size() == 0 || origVoltArray.size() != origGsArray.size())
            return;
        ArrayList<Double> newVoltArray = new ArrayList<Double>();
        ArrayList<Double> newGsArray = new ArrayList<Double>();
        newGsArray.add(origGsArray.get(0));
        for (int i = 0; i < newMafTable.getColumnCount(); ++i) {
            if (Pattern.matches(Utils.fpRegex, newMafTable.getValueAt(0, i).toString()))
                newVoltArray.add(Double.valueOf(newMafTable.getValueAt(0, i).toString()));
            else
                break;
        }
        if (newVoltArray.size() != origVoltArray.size())
            return;
        calculateNewGs(newVoltArray, newGsArray);
        for (int i = 0; i < newVoltArray.size(); ++i)
            newMafTable.setValueAt(newGsArray.get(i), 1, i);
        corrMafData.clear();
        setXYSeries(corrMafData, newVoltArray, newGsArray);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e);
    }
}

From source file:com.ephesoft.dcma.tablefinder.share.TableExtractionResultModifierUtility.java

/**
 * Checks if a string matches with regex pattern.
 * //from w w  w.  ja  v a 2  s  . c  o m
 * @param value {@link String}
 * @param pattern {@link String}
 * @return boolean True if value matches pattern else false.
 */
public static boolean isValidWithPattern(final String value, final String pattern) {
    boolean isValid = true;
    if (!EphesoftStringUtil.isNullOrEmpty(pattern) && value != null) {
        LOGGER.info("Validation Pattern for the Column is : ", pattern);
        isValid = Pattern.matches(pattern, value.trim());
    }
    return isValid;
}

From source file:egovframework.rte.fdl.string.EgovStringUtil.java

/**
 * It converts the string representation of a
 * number to integer type (eg. '27' -> 27)
 * /*from  w  w  w  .jav a2s . c o m*/
 * <pre>
 * StringUtil.string2integer('14')    = 14
 * </pre>
 * @param str
 *        string representation of a number
 * @return integer integer type of string public
 *         static int string2integer(String str) {
 *         int ret = Integer.parseInt(str.trim());
 *         return ret; } /** It converts integer
 *         type to String ( 27 -> '27')
 * 
 *         <pre>
 * StringUtil.integer2string(14)    = '14'
 * </pre>
 * @param integer
 *        integer type
 * @return String string representation of a number
 *         public static String integer2string(int
 *         integer) { return ("" + integer); } /**
 *         It returns true if str matches the
 *         pattern string. It performs regular
 *         expression pattern matching.
 * 
 *         <pre>
 * StringUtil.isPatternMatching('abc-def', '*-*')    = true
 * StringUtil.isPatternMatching('abc', '*-*')    = false
 * </pre>
 * @param str
 *        original String
 * @param pattern
 *        pattern String
 * @return boolean which matches the pattern string
 *         or not.
 * @throws Exception
 *         fail to check pattern matched
 */
public static boolean isPatternMatching(String str, String pattern) throws Exception {
    // if url has wild key, i.e. "*", convert it to
    // ".*" so that we can
    // perform regex matching
    if (pattern.indexOf('*') >= 0) {
        pattern = pattern.replaceAll("\\*", ".*");
    }

    pattern = "^" + pattern + "$";

    return Pattern.matches(pattern, str);
}

From source file:com.datatorrent.stram.webapp.TypeGraph.java

/**
 * @param clazz parent class/*from   w  w  w.  ja va  2  s  .com*/
 * @param filter
 * @param packagePrefix 
 * @param startsWith  case insensitive
 * @return all instantiable descendants of class clazz which comfort to filter expression, packagePrefix and start with $startsWith
 */
public List<String> getInstantiableDescendants(String clazz, String filter, String packagePrefix,
        String startsWith) {
    TypeGraphVertex tgv = typeGraph.get(clazz);
    if (tgv == null) {
        return null;
    }

    List<String> result = new LinkedList<String>();
    if (tgv != null) {

        for (TypeGraphVertex node : tgv.allInstantiableDescendants) {
            String typeName = node.typeName;
            if (filter != null && !Pattern.matches(filter, node.typeName)) {
                continue;
            }
            if (packagePrefix != null && !node.typeName.startsWith(packagePrefix)) {
                continue;
            }
            if (startsWith != null && !typeName.substring(typeName.lastIndexOf('.') + 1).toLowerCase()
                    .startsWith(startsWith.toLowerCase())) {
                continue;
            }
            result.add(node.typeName);
        }
    }
    return result;
}

From source file:org.agnitas.beans.impl.RecipientImpl.java

/**
 * Checks if E-Mail-Adress given in customerData-HashMap is valid
 * /*from w w  w . jav  a  2  s  . c o m*/
 * @return true if E-Mail-Adress is valid
 */
@Override
public boolean emailValid() {
    String email = (String) custParameters.get("email");

    if (email == null) {
        return false;
    }
    email = email.trim();
    if (email == null) {
        return false;
    }

    if (!Pattern.matches("[^<@]+@[^<@.]+[.][^<@]+", email)) {
        return false;
    }
    return true;
}

From source file:com.hp.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject searchListItems(String logicalListName, String term, long workspaceId, boolean multiValue,
        boolean extensible) {
    int defaultSize = 10;
    JSONObject ret = new JSONObject();

    MqmRestClient client;//from  ww w. ja  v  a 2s . c  o m
    try {
        client = createClient();
    } catch (ClientException e) {
        logger.warn(PRODUCT_NAME + " connection failed", e);
        return error(e.getMessage(), e.getLink());
    }
    try {

        PagedList<ListItem> listItemPagedList = client.queryListItems(logicalListName, term, workspaceId, 0,
                defaultSize);
        List<ListItem> listItems = listItemPagedList.getItems();
        boolean moreResults = listItemPagedList.getTotalCount() > listItems.size();

        JSONArray retArray = new JSONArray();
        if (moreResults) {
            retArray.add(createMoreResultsJson());
        }

        if (!multiValue) {
            String quotedTerm = Pattern.quote(term.toLowerCase());
            if (Pattern.matches(".*" + quotedTerm + ".*", NOT_SPECIFIED.toLowerCase())) {
                JSONObject notSpecifiedItemJson = new JSONObject();
                notSpecifiedItemJson.put("id", -1);
                notSpecifiedItemJson.put("text", NOT_SPECIFIED);
                retArray.add(notSpecifiedItemJson);
            }
        }

        for (ListItem item : listItems) {
            if (!toBeFiltered(item)) {
                JSONObject itemJson = new JSONObject();
                itemJson.put("id", item.getId());
                itemJson.put("text", item.getName());
                retArray.add(itemJson);
            }

        }
        // we shall use "if (extensible){}" on following line, but we do not have UI ready for the case: multiValue = true & extensible = true
        if (extensible && !multiValue) {
            //if exactly one item matches, we do not want to bother user with "new value" item
            if ((listItems.size() != 1)
                    || (!listItems.get(0).getName().toLowerCase().equals(term.toLowerCase()))) {
                retArray.add(createNewValueJson("0"));
            }
        }

        ret.put("results", retArray);
    } catch (RequestException e) {
        logger.warn("Failed to retrieve list items", e);
        return error("Unable to retrieve job configuration");
    }

    return ret;
}

From source file:com.ephesoft.dcma.gwt.core.server.DCMARemoteServiceServlet.java

@Override
public Boolean validateValueWithRegEx(final String input, final String regex) {
    boolean isValidInput = true;
    try {/*from   w  w  w  .  j a v  a 2 s  . c  o  m*/
        isValidInput = Pattern.matches(regex, input);
    } catch (PatternSyntaxException e) {
        isValidInput = false;
    }
    return isValidInput;
}

From source file:com.eurelis.opencms.workflows.functions.EmailNotificationFunction.java

/**
 * Extract the list of receivers from the given recieverString that contains the list of address email concatened
 * with a ";". It contains also some opencms properties name that need to be collected and converted into email
 * address thanks opencms user manager./*  w w w .  j av  a2s. com*/
 * 
 * @param receiverString
 *            the list of receiver "encoded"
 * @param cmsObject
 *            the cmsObject that will allow to get some information into openCms
 * @param listOfFiles
 *            the list of files associated to the workflow
 * @return the list of email address of receivers, an <i>Empty list</i> if none address are valid
 */
private List<String> extractListOfReceivers(String receiverString, CmsObject cmsObject,
        List<String> listOfFiles) {

    // get all sub string (remove separator)
    String[] arrayOfEmails = receiverString
            .split(ModuleConfigurationLoader.getConfiguration().WORKFLOW_RIGHTCONFIGFILE_PARAMETER_SEPARATOR);

    /*
     * Treat each email and check that it is a valid email. If not, check that it's not a property. In the case that
     * is a property, treat it to get the email address contained into opencms account manager.
     */
    for (int addressIndex = 0; addressIndex < arrayOfEmails.length; addressIndex++) {
        String emailAddress = arrayOfEmails[addressIndex];
        // remove the "return" if there is one
        if (emailAddress.startsWith("\n")) {
            emailAddress = emailAddress.substring(1);
        }
        // check that it is not a opencms property (kw = opencms)
        else if (emailAddress.startsWith(OPENCMSPROPERTY_STARTSTRING)) {
            this.extractEmailAddressFromProperty(
                    emailAddress.trim().substring(OPENCMSPROPERTY_STARTSTRING.length()), cmsObject,
                    listOfFiles);
        }
        // check that it is not a workfklow property (kw = instance)
        else if (emailAddress.startsWith(WORKFLOWPROPERTY_STARTSTRING)) {
            this.extractEmailAddressFromWorkflowProperty(
                    emailAddress.trim().substring(WORKFLOWPROPERTY_STARTSTRING.length()), cmsObject);
        }
        // check that it is not a workfklow parameter (kw = parameter)
        else if (emailAddress.startsWith(WORKFLOWPARAMETER_STARTSTRING)) {
            this.extractEmailAddressFromParameter(
                    emailAddress.trim().substring(WORKFLOWPARAMETER_STARTSTRING.length()), cmsObject);
        } else {
            // check that it is a valid email address
            if (Pattern.matches(EMAIL_PATTERN, emailAddress)) {
                // add associated files to the reviewer
                this.addResourcesInMap(emailAddress, listOfFiles);
            } else {
                LOGGER.warn("The email address " + emailAddress + " is not valid.");
            }
        }
    }
    return new ArrayList<String>(_resourcesPerReviewer.keySet());
}