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:org.apache.calcite.runtime.SqlFunctions.java

/** SQL {@code LIKE} function. */
public static boolean like(String s, String pattern) {
    final String regex = Like.sqlToRegexLike(pattern, null);
    return Pattern.matches(regex, s);
}

From source file:com.oncore.calorders.core.utils.FormatHelper.java

/**
 * Checks if the CharSequence is a valid web URL
 *
 * <pre>/*  ww w .jav a 2 s .  c  om*/
 * PageUtilities.isValidURL(null) = false
 * PageUtilities.isValidURL("") = false
 * PageUtilities.isValidURL(" ") = false
 * PageUtilities.isValidURL("abc") = false
 * PageUtilities.isValidURL("www.yahoo.com") = true
 * </pre>
 *
 * @author OnCore Consulting LLC
 *
 * @param url a URL to validate
 *
 *
 * @return true if the value is a valid address, false otherwise
 */
public static Boolean isValidURL(final String url) {
    Boolean result = Boolean.FALSE;

    if (StringUtils.isNotBlank(url)) {
        try {
            result = Pattern.matches(
                    "(@)?(href=')?(HREF=')?(HREF=\")?(href=\")?(http://)?[a-zA-Z_0-9\\-]+(\\.\\w[a-zA-Z_0-9\\-]+)+(/[#&\\n\\-=?\\+\\%/\\.\\w]+)?",
                    url);
        } catch (PatternSyntaxException px) {
            Logger.warn(LOG, "Invalid URL pattern detected");
        } catch (Exception ex) {
            Logger.warn(LOG, "Fatal error occurred during email validation check");
        }
    }

    return result;
}

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

/**
 * Verifica se um IP  vlido na notao de IP.
 * @param ip o IP a ser verificado.//from  w  ww  .  j a  va  2 s.c o m
 * @return verdadeiro se um IP  vlido na notao de IPv4.
 */
public static boolean isValidIPv4(String ip) {
    if (ip == null) {
        return false;
    } else {
        return Pattern.matches("^" + "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}"
                + "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" + "$", ip);
    }
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

/** SQL {@code LIKE} function with escape. */
public static boolean like(String s, String pattern, String escape) {
    final String regex = Like.sqlToRegexLike(pattern, escape);
    return Pattern.matches(regex, s);
}

From source file:nl.mpi.lamus.metadata.implementation.LamusMetadataApiBridge.java

/**
 * @see MetadataApiBridge#getComponentPathForProfileAndReferenceType(
 *  java.net.URI, java.lang.String, nl.mpi.lamus.workspace.model.WorkspaceNodeType, boolean)
 *//*from ww w .  ja  v a2 s  . c o  m*/
@Override
public String getComponentPathForProfileAndReferenceType(URI profileLocation, String referenceMimetype,
        WorkspaceNodeType referenceNodeType, boolean isInfoLink) {

    logger.trace("Profile location URI: " + profileLocation.toString() + "; Reference mime type: "
            + referenceMimetype + "; Reference node type: " + referenceNodeType + "; isInfoLink: "
            + isInfoLink);

    if (referenceMimetype == null && referenceNodeType == null) {
        return null;
    }

    CmdiProfile matchedProfile = getProfileWithLocation(profileLocation);

    logger.trace("Matched profile: " + matchedProfile.toString());

    if (matchedProfile != null) {
        boolean usingMimetype = true;
        Map<String, String> componentMap;

        if (referenceMimetype != null) {
            componentMap = matchedProfile.getComponentsByMimetypeMap();
        } else {
            usingMimetype = false;
            componentMap = matchedProfile.getComponentsByNodeTypeMap();
        }

        if (componentMap != null && !componentMap.isEmpty()) {
            Set<Map.Entry<String, String>> entrySet = componentMap.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {

                logger.trace("Component entry: " + entry);

                String typeToCheck = usingMimetype ? referenceMimetype : referenceNodeType.name();
                if (isInfoLink && usingMimetype) {
                    typeToCheck = "info";
                }

                logger.trace("Entry key: " + entry.getKey() + "; Type to check: " + typeToCheck);

                if (Pattern.matches(entry.getKey(), typeToCheck)) {
                    return entry.getValue();
                }
            }
        }
    }

    String message = "CMDI Profile [" + (matchedProfile != null ? matchedProfile.getId() : "null")
            + "] has no component types configured. Reference will not be added to parent.";
    logger.warn(message);
    return null;
}

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

/**
 * Verifica se um IP  vlido na notao de IP.
 * @param ip o IP a ser verificado.//from   www.j a va2  s  .  com
 * @return verdadeiro se um IP  vlido na notao de IPv6.
 */
public static boolean isValidIPv6(String ip) {
    if (ip == null) {
        return false;
    } else {
        ip = ip.trim();
        ip = ip.toLowerCase();
        return Pattern.matches("^" + "([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|" + "([0-9a-fA-F]{1,4}:){1,7}:|"
                + "([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|"
                + "([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|"
                + "([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|"
                + "([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|"
                + "([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|"
                + "[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|" + ":((:[0-9a-fA-F]{1,4}){1,7}|:)|"
                + "fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}" + "$", ip);
    }
}

From source file:com.tacitknowledge.util.migration.jdbc.SqlScriptMigrationTask.java

/**
 * Parses the SQL/DDL to execute and returns a list of individual statements.  For database
 * types that support mulitple statements in a single <code>Statement.execute</code> call,
 * this method will return a one-element <code>List</code> containing the entire SQL
 * file.//from w  w  w .ja v  a 2s.  c o m
 *
 * @param context the MigrationContext, to figure out db type and if it
 *                can handle multiple statements at once
 * @return a list of SQL and DDL statements to execute
 */
public List getSqlStatements(JdbcMigrationContext context, String sqlStatements) {
    List statements = new ArrayList();
    if (context.getDatabaseType().isMultipleStatementsSupported()) {
        statements.add(sqlStatements);
        return statements;
    }

    StringBuffer currentStatement = new StringBuffer();
    boolean inQuotedString = false;
    boolean inComment = false;
    char[] sqlChars = sqlStatements.toCharArray();
    for (int i = 0; i < sqlChars.length; i++) {
        if (sqlChars[i] == '\n') {
            inComment = false;
        }

        if (!inComment) {
            switch (sqlChars[i]) {
            case '-':
            case '/':
                if (!inQuotedString && i + 1 < sqlChars.length && sqlChars[i + 1] == sqlChars[i]) {
                    inComment = true;
                } else {
                    currentStatement.append(sqlChars[i]);
                }
                break;
            case '\'':
                inQuotedString = !inQuotedString;
                currentStatement.append(sqlChars[i]);
                break;
            case ';':
                if (!inQuotedString) {
                    // If we're in a stored procedure, just keep rolling
                    if (isStoredProcedure(context.getDatabaseType().getDatabaseType(),
                            currentStatement.toString())) {
                        currentStatement.append(sqlChars[i]);
                    } else {
                        statements.add(currentStatement.toString().trim());
                        currentStatement = new StringBuffer();
                    }
                } else {
                    currentStatement.append(sqlChars[i]);
                }
                break;
            /* sybase uses 'GO' as it's statement delimiter */
            case 'g':
            case 'G':
                /*
                 * Build up a string, reading backwards from the current index to
                 * the previous newline (or beginning of sequence) and from the
                 * current index up to the next newline.  If it matches the regex
                 * for the GO delimiter, then add the statement otherwise
                 * just append the current index's character to currentStatement
                 */
                if (context.getDatabaseType().getDatabaseType().equals("sybase")) {
                    // read from current index to previous line terminator 
                    // or start of sequence
                    StringBuffer previous = new StringBuffer();
                    for (int j = i - 1; j >= 0; j--) {
                        char c = sqlChars[j];
                        previous.append(c);
                        if (isLineTerminator(c)) {
                            break;
                        }
                    }

                    // reverse previous, since we've been walking backwards, but appending
                    previous = previous.reverse();

                    // read from current index to upcoming line terminator 
                    // or end of sequence.  If it is the GO delimiter, 
                    // we skip up to line terminator
                    StringBuffer after = new StringBuffer();
                    int newIndex = 0;
                    for (int k = i + 1; k < sqlChars.length; k++) {
                        char c = sqlChars[k];
                        after.append(c);
                        newIndex = k;
                        if (isLineTerminator(c)) {
                            break;
                        }
                    }

                    // check against the pattern if its a GO delimiter
                    String possibleDelimiter = previous.append(sqlChars[i]).append(after).toString();
                    final String delimiterPattern = "^\\s*[Gg][Oo]\\s*$";

                    if (Pattern.matches(delimiterPattern, possibleDelimiter)) {
                        // if it's blank, don't bother adding it since Sybase
                        // will complain about empty queries.
                        // This happens if there are two GO's with no
                        // actual SQL to run between them.
                        if (!StringUtils.isBlank(currentStatement.toString().trim())) {
                            statements.add(currentStatement.toString().trim());
                        }
                        currentStatement = new StringBuffer();
                        // skip up to next line terminator
                        i = newIndex;
                    } else // not a delimiter, so just append
                    {
                        currentStatement.append(sqlChars[i]);
                    }
                } else // not a sybase db, so just append
                {
                    currentStatement.append(sqlChars[i]);
                }
                break;
            default:
                currentStatement.append(sqlChars[i]);
                break;
            }
        }
    }
    if (currentStatement.toString().trim().length() > 0) {
        statements.add(currentStatement.toString().trim());
    }

    return statements;
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

/** SQL {@code SIMILAR} function. */
public static boolean similar(String s, String pattern) {
    final String regex = Like.sqlToRegexSimilar(pattern, null);
    return Pattern.matches(regex, s);
}

From source file:de.dmarcini.bt.homelight.HomeLightMainActivity.java

/**
 * Vorprfen, falls Infos kommen die schon hier abgearbetet werden knnen
 * wie zum Beispiel getRGBW oder getType
 *
 * @param data Kommandostring//from   ww w.  java  2  s  .co m
 * @return Wurden die Daten schon abgearbetet?
 */
private String[] onBTDataAvaiable(String data) {
    String[] param;
    int cmdNum;

    //
    // Kommando empfangen
    //
    param = data.split(":");
    if (Pattern.matches(ProjectConst.KOMANDPATTERN, data) && (param.length > 0)) {
        //
        // Hier mal das Kommando finden und umrechnen
        //
        try {
            cmdNum = Integer.parseInt(param[0], 16);
        } catch (NumberFormatException ex) {
            cmdNum = ProjectConst.C_UNKNOWN;
        }
        //
        // Jetzt Kommando auswerten
        //
        switch (cmdNum) {
        //
        // Unbekanntes Kommando
        //
        case ProjectConst.C_UNKNOWN:
            Log.e(TAG, "unknown command recived! Ignored.");
            return (null);

        //
        // Frage nach dem Typ / Antwort
        //
        case ProjectConst.C_ASKTYP:
            if (BuildConfig.DEBUG) {
                Log.v(TAG, "Modul type recived! <" + data + ">");
            }
            if (param.length == 2 && param[1] != null) {
                btConfig.setModuleType(param[1]);
            }
            return (null);

        //
        // Frage nach dem Modulname / Antwort
        //
        case ProjectConst.C_ASKNAME:
            if (BuildConfig.DEBUG) {
                Log.v(TAG, "Modul name recived! <" + data + ">");
            }
            if (param.length == 2 && param[1] != null) {
                btConfig.setModuleName(param[1]);
            }
            return (null);

        //
        // Frage nach RGBW
        //
        case ProjectConst.C_ASKRGBW:
            //
            // Weitergeben an die Fragmente
            //
            if (BuildConfig.DEBUG) {
                Log.v(TAG, "RGBW from module <" + data + ">");
            }
            if (param.length != ProjectConst.C_ASKRGB_LEN) {
                return (null);
            }
            fillValuesInArray(param);
            return (param);

        //
        // Sende COLOR
        //
        case ProjectConst.C_SETCOLOR:
            if (BuildConfig.DEBUG) {
                Log.v(TAG, "SET RGBW to module (should not done)  <" + data + ">");
            }
            return (param);

        default:
            Log.e(TAG, "default: send to handler....");
            return (param);
        }
    } else {
        Log.e(TAG, "wrong command string recived! Ignored.");
    }
    return (null);
}

From source file:fr.fastconnect.factory.tibco.bw.maven.packaging.MergePropertiesMojo.java

/**
 * <p>//from ww  w  .j a  va  2 s.  c om
 * This expands wild cards properties.<br /><br />
 * Both wildcard expressions and expressions to expand are present in the
 * same properties object.<br /><br />
 * <i>Example</i>
 *  <ul>
 *     <li><b>property with wildcard</b>: /root/element[*]/key=new_value</li>
 *     <li><b>property matching</b>: /root/element[my_name]/key=old_value</li>
 *  </ul>
 *  will expand to:<br />
 *  <ul>
 *     <li><b>property after expansion</b>:
 * /root/element[my_name]/key=new_value</li>
 *  </ul>
 * </p>
 * 
 * @param properties, the properties object with wildcard expressions and
 * expressions to expand
 * @return properties with expanded expressions, but without wildcard
 * expressions
 */
protected Properties expandWildCards(Properties properties) {
    Properties propertiesWithWildCards = new Properties() { // sorted properties
        private static final long serialVersionUID = 7793482336210629858L;

        @Override
        public synchronized Enumeration<Object> keys() {
            return Collections.enumeration(new TreeSet<Object>(super.keySet()));
        }
    };
    String key;

    // retrieve the keys with WildCards
    Enumeration<Object> e = properties.keys();
    while (e.hasMoreElements()) {
        key = (String) e.nextElement();
        if (isAWildCard(key)) {
            propertiesWithWildCards.setProperty(key, properties.getProperty(key));
            properties.remove(key);
        }
    }

    // try to replace the values of other keys matching the keys with WildCards
    Enumeration<Object> w = propertiesWithWildCards.keys();
    while (w.hasMoreElements()) {
        String keyWithWildCards = (String) w.nextElement();
        String regex = wildcardToRegex(keyWithWildCards);

        String ignoreWildcardInVariablesPattern = "(.*)variables\\\\\\[(.*)\\\\\\]\\/variable\\\\\\[(.*)\\\\\\](.*)";
        Pattern p = Pattern.compile(ignoreWildcardInVariablesPattern);
        Matcher m = p.matcher(regex);
        if (m.matches()) {
            String variables = m.group(2);
            String variable = m.group(3);
            variables = variables.replace(".*", "\\*");
            variable = variable.replace(".*", "\\*");
            regex = m.group(1) + "variables\\[" + variables + "\\]/variable\\[" + variable + "\\]" + m.group(4);
        }

        Boolean found = false;

        e = properties.keys();
        while (e.hasMoreElements()) {
            key = (String) e.nextElement();

            if (Pattern.matches(regex, key)) {
                found = true;
                String value = (String) propertiesWithWildCards.getProperty(keyWithWildCards);
                properties.setProperty(key, value);
            }
        }

        // not found, we put back the expression with wild cards in the original list (false positive)
        // this way the wildcard can still be used in a next pass and will be removed at the end by AbstractPackagingMojo.removeWildCards 
        if (!found) {
            properties.setProperty(keyWithWildCards, propertiesWithWildCards.getProperty(keyWithWildCards));
        }
    }

    return properties;
}