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.mindcognition.mindraider.application.model.outline.OutlineCustodian.java

/**
 * TWiki import./*from   w w w .  java2s.  c o  m*/
 * @param srcFileName
 */
private void twikiImport(String srcFileName, ProgressDialogJFrame progressDialogJFrame) throws Exception {
    logger.debug("=-> TWiki import: " + srcFileName);

    // DO NOT BUILD EXPANDED NOTEBOOK, but create new notebook, build URIs
    // and use notebook custodian
    // to add concepts into that notebook
    // o you must track path up to the root to know where to add parent

    // file reader and read line by line...
    // o from begin to the first ---++ store to the annotation of the newly
    // created notebook
    // o set label property to the name of the top level root ---+

    FileReader fileReader = new FileReader(srcFileName);
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    // create new notebook in TWiki import folder
    String folderUri = MindRaider.labelCustodian.LABEL_TWIKI_IMPORT_URI;
    String notebookUri = null;
    MindRaider.labelCustodian.create("TWiki Import", MindRaider.labelCustodian.LABEL_TWIKI_IMPORT_URI);

    String[] parentConceptUris = new String[50];

    String notebookLabel, line;
    String lastConceptName = null;
    StringBuffer annotation = new StringBuffer();
    while ((line = bufferedReader.readLine()) != null) {

        // match for section
        if (Pattern.matches("^---[+]+ .*", line)) {
            // if it is root, take the label
            if (Pattern.matches("^---[+]{1} .*", line)) {
                notebookLabel = line.substring(5);
                logger.debug("LABEL: " + notebookLabel);

                notebookUri = MindRaiderVocabulary.getNotebookUri(Utils.toNcName(notebookLabel));
                String createdUri;

                while (MindRaiderConstants.EXISTS
                        .equals(createdUri = create(notebookLabel, notebookUri, null, false))) {
                    notebookUri += "_";
                }
                notebookUri = createdUri;
                MindRaider.labelCustodian.addOutline(folderUri, notebookUri);
                // set source TWiki file property
                activeOutlineResource.resource.addProperty(new SourceTwikiFileProperty(srcFileName));
                activeOutlineResource.save();
                logger.debug("Notebook created: " + notebookUri);
            } else {
                twikiImportProcessLine(progressDialogJFrame, notebookUri, parentConceptUris, lastConceptName,
                        annotation);
                lastConceptName = line;
            }
            logger.debug(" SECTION: " + line);
        } else {

            // read annotation of the current concept
            annotation.append(line);
            annotation.append("\n");
        }
    }
    // add the last opened section
    twikiImportProcessLine(progressDialogJFrame, notebookUri, parentConceptUris, lastConceptName, annotation);

    // close everything
    fileReader.close();

    // now refresh notebook outline
    ExplorerJPanel.getInstance().refresh();
    OutlineJPanel.getInstance().refresh();
    MindRaider.spidersGraph.renderModel();
    // note that back export to twiki button is enabled to according to
    // "TWiki source" property
    // of the active notebook
}

From source file:com.vuze.plugin.azVPN_Air.Checker.java

private boolean matchesVPNIP(InetAddress address) {
    if (address == null) {
        return false;
    }/* w  ww  .  j  a  v a 2 s.co  m*/
    String regex = config.getPluginStringParameter(PluginAir.CONFIG_VPN_IP_MATCHING);
    return Pattern.matches(regex, address.getHostAddress());
}

From source file:com.ah.ui.actions.hiveap.HiveApFileAction.java

/**
 * Get the image product name and version from the header xml string
 *
 *@param lineStr -/*from  w  ww  .j a v  a2s  .  c  om*/
 *@return HiveApImageInfo
 */
private HiveApImageInfo getImageInfoHead(String lineStr) {
    try {
        if (!lineStr.startsWith("#!/bin/bash") || !lineStr.contains("<Image-Header")
                || !lineStr.contains("</Image-Header>") || !lineStr.contains("<Firmware>")
                || !lineStr.contains("</Firmware>")) {
            return null;
        }
        HiveApImageInfo info = new HiveApImageInfo();
        SAXReader reader = new SAXReader();
        String docName = lineStr.substring(lineStr.indexOf("<Firmware>"),
                lineStr.indexOf("</Firmware>") + "</Firmware>".length());
        Document doc = reader.read(new StringReader(docName));
        Element roota = doc.getRootElement();
        Iterator<?> iter = roota.elementIterator();
        Element foo;
        while (iter.hasNext()) {
            foo = (Element) iter.next();
            // get product name
            if (foo.getName().equalsIgnoreCase("Product")) {
                info.setProductName(foo.getStringValue());
                // get image version
            } else if (foo.getName().equalsIgnoreCase("Version")) {
                iter = foo.elementIterator();
                while (iter.hasNext()) {
                    foo = (Element) iter.next();
                    if (foo.getName().equalsIgnoreCase("External")) {
                        iter = foo.elementIterator();
                        while (iter.hasNext()) {
                            foo = (Element) iter.next();
                            // get major version
                            if (foo.getName().equalsIgnoreCase("Major")) {
                                info.setMajorVersion(foo.getStringValue());

                                // get minor version
                            } else if (foo.getName().equalsIgnoreCase("Minor")) {
                                info.setMinorVersion(foo.getStringValue());

                                // get release version
                            } else if (foo.getName().equalsIgnoreCase("Release")) {
                                info.setRelVersion(foo.getStringValue());

                                // get patch string
                            } else if (foo.getName().equalsIgnoreCase("Patch")) {
                                try {
                                    info.setImageUid(Integer.parseInt(foo.getStringValue()));
                                } catch (NumberFormatException nfe) {
                                    info.setImageUid(0);
                                }
                            }
                        }
                    }
                }
            }
        }
        String regex = "^\\d+\\.+\\d+r\\d+\\w*$";
        // check the product name and version format
        if ("".equals(info.getProductName()) || !Pattern.matches(regex, info.getImageVersion().trim())) {
            return null;
        }
        com.ah.be.config.image.ImageManager.updateHiveApImageInfo(info);
        return info;
    } catch (Exception ex) {
        log.error("checkImageInfo : ", ex.getMessage());
        return null;
    }
}

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

/**
 * Contact the account manager of open cms to get the email of the reviewer
 * //from   w  ww  .jav a 2s .c o m
 * @param reviewerName
 *            the login of the reviewer
 * @param cmsObject
 *            cmsObject the cmsObject that will allow to get some information into openCms
 * @return the required email, <b>null</b> if any problem occurs (see logs for details)s
 */
private String getEmailAddressFromAccountManager(String reviewerName, CmsObject cmsObject) {

    // List list = OpenCms.getOrgUnitManager().getUsers(obj, "/", true);
    try {
        if (StringChecker.isNotNullOrEmpty(reviewerName)) {
            CmsUser userObject = cmsObject.readUser(reviewerName);
            String email = userObject.getEmail().trim();

            // Check that the email is valid
            if (StringChecker.isNotNullOrEmpty(email) && Pattern.matches(EMAIL_PATTERN, email)) {
                return email;
            } else
                return null;
        }
    } catch (CmsException e) {
        LOGGER.error(ErrorFormatter.formatException(e));
    }
    return null;
}

From source file:de.tum.in.bluetooth.discovery.BluetoothDeviceDiscovery.java

/**
 * Used to pair {@link RemoteDevice}/*from  w w  w  .  java  2  s . c o  m*/
 *
 * @param device
 *            The currently discovered Remote Device
 * @return if paired then true else false
 */
private boolean pair(final RemoteDevice device) {
    if ((this.m_fleet == null) || (this.m_fleet.getDevices() == null)) {
        LOGGER.info("Ignoring autopairing - no fleet configured");
        return true;
    }

    final String address = device.getBluetoothAddress();
    final String name = this.getDeviceName(device);

    if ((name == null) && this.m_ignoreUnnamedDevices) {
        LOGGER.warn("Pairing not attempted, ignoring unnamed devices");
        return false;
    }

    final List<Device> devices = this.m_fleet.getDevices();
    for (final Device model : devices) {
        final String regex = model.getId();
        final String pin = model.getPin();
        if (Pattern.matches(regex, address) || ((name != null) && Pattern.matches(regex, name))) {
            LOGGER.info("Paring pattern match for " + address + " / " + name + " with " + regex);
            try {
                LOGGER.info("Device " + address + " pairing started..");
                final boolean authStatus = RemoteDeviceHelper.authenticate(device, pin);
                LOGGER.info("Device (" + address + ") Pairing Authentication Status: " + authStatus);
                return true;
            } catch (final IOException e) {
                LOGGER.error("Cannot authenticate device despite it matches the regex " + regex, e);
            }
        }
    }
    return false;
}

From source file:com.compal.telephonytest.TelephonyTest.java

public boolean checkGsmDeviceId(String deviceId) {
    // IMEI may include the check digit
    String imeiPattern = "[0-9]{14,15}";
    int expectedCheckDigit = getLuhnCheckDigit(deviceId.substring(0, 14));
    int actualCheckDigit = Character.digit(deviceId.charAt(14), 10);
    if (Pattern.matches(imeiPattern, deviceId)) {
        if (deviceId.length() == 15)
            if (expectedCheckDigit == actualCheckDigit)
                return true;
        return true;
    }//w  ww . j av  a 2 s . co  m
    return false;
}

From source file:es.emergya.ui.plugins.admin.aux1.SummaryAction.java

private JPanel buildPanelFilter(final String topLabel, final int textfieldSize, final Dimension dimension,
        final JList list, final boolean left) {
    JPanel left_filtro = new JPanel(new GridBagLayout());
    left_filtro.setPreferredSize(dimension);
    left_filtro.setOpaque(false);//from w  w w. j  ava 2s  . c  om
    final GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.BASELINE_LEADING;
    left_filtro.add(new JLabel(topLabel, JLabel.LEFT), gbc);

    final JTextField filtro = new JTextField(textfieldSize);
    gbc.gridy++;
    left_filtro.add(filtro, gbc);

    AbstractAction actionStartFilter = new AbstractAction(null, getIcon("Buttons.noFiltrar")) {

        private static final long serialVersionUID = -4737487889360372801L;

        @Override
        public void actionPerformed(ActionEvent e) {
            ((DefaultListModel) list.getModel()).removeAllElements();
            filtro.setText(null);
            if (left) {
                for (Object obj : leftItems) {
                    ((DefaultListModel) list.getModel()).addElement(obj);
                }
            } else {
                for (Object obj : rightItems) {
                    ((DefaultListModel) list.getModel()).addElement(obj);
                }
            }

        }
    };
    AbstractAction actionStopFilter = new AbstractAction(null, getIcon("Buttons.filtrar")) {

        private static final long serialVersionUID = 6570608476764008290L;

        @Override
        public void actionPerformed(ActionEvent e) {
            ((DefaultListModel) list.getModel()).removeAllElements();
            if (left) {
                for (Object obj : leftItems) {
                    if (compare(filtro, obj)) {
                        ((DefaultListModel) list.getModel()).addElement(obj);
                    }
                }
            } else {
                for (Object obj : rightItems) {
                    if (compare(filtro, obj)) {
                        ((DefaultListModel) list.getModel()).addElement(obj);
                    }
                }
            }
        }

        private boolean compare(final JTextField filtro, Object obj) {
            final String elemento = obj.toString().toUpperCase().trim();
            final String text = filtro.getText().toUpperCase().trim();

            final String pattern = text.replace("*", ".*");
            boolean res = Pattern.matches(pattern, elemento);

            return res;// || elemento.indexOf(text) >= 0;
        }
    };
    JButton jButton = new JButton(actionStartFilter);
    JButton jButton2 = new JButton(actionStopFilter);
    jButton.setBorderPainted(false);
    jButton2.setBorderPainted(false);
    jButton.setContentAreaFilled(false);
    jButton2.setContentAreaFilled(false);
    jButton.setPreferredSize(
            new Dimension(jButton.getIcon().getIconWidth(), jButton.getIcon().getIconHeight()));
    jButton2.setPreferredSize(
            new Dimension(jButton2.getIcon().getIconWidth(), jButton2.getIcon().getIconHeight()));

    gbc.gridx++;
    left_filtro.add(jButton2, gbc);
    gbc.gridx++;
    left_filtro.add(jButton, gbc);
    return left_filtro;
}

From source file:de.interactive_instruments.ShapeChange.Options.java

/** This returns the names of all parms whose names match a regex pattern */
public String[] parameterNamesByRegex(String t, String regex) {
    HashSet<String> pnames = new HashSet<String>();
    int lt2 = t.length() + 2;
    for (Entry<String, String> e : fParameters.entrySet()) {
        String key = e.getKey();//from  ww w  .ja v a  2 s .  com
        if (key.startsWith(t + "::")) {
            if (Pattern.matches(regex, key.substring(lt2)))
                pnames.add(key.substring(lt2));
        }
    }
    return pnames.toArray(new String[0]);
}

From source file:net.spfbl.spf.SPF.java

/**
 * Verifica se o whois  um mecanismo a vlido.
 *
 * @param token o whois a ser verificado.
 * @return verdadeiro se o whois  um mecanismo a vlido.
 *//*from  w ww  .  j  a va2s  .c  o  m*/
private static boolean isMechanismA(String token) {
    token = expand(token, "127.0.0.1", "sender@domain.tld", "host.domain.tld");
    return Pattern.matches("^" + "(\\+|-|~|\\?)?a"
            + "(:(?=.{1,255}$)[0-9A-Za-z_](?:(?:[0-9A-Za-z_]|-){0,61}[0-9A-Za-z_])?(?:\\.[0-9A-Za-z_](?:(?:[0-9A-Za-z_]|-){0,61}[0-9A-Za-z_])?)*\\.?)?"
            + "(/[0-9]{1,2})?(//[0-9]{1,3})?" + "$", token.toLowerCase());
}

From source file:com.roche.sequencing.bioinformatics.common.utils.FileUtil.java

public static File getMatchingDirectoryRelativeToBaseDirectory(File baseDirectory,
        String[] regularExpressionsForRelativeFolders) {
    File currentDirectory = baseDirectory;
    for (String regularExpressionForNextFolder : regularExpressionsForRelativeFolders) {
        if (regularExpressionForNextFolder.equals(".")) {
            // stay in the current directory
        } else if (regularExpressionForNextFolder.equals("..")) {
            currentDirectory = currentDirectory.getParentFile();
        } else {//  www  . ja v  a  2 s. co m
            List<File> matchingFiles = new ArrayList<File>();
            for (File childFile : currentDirectory.listFiles()) {
                if (childFile.isDirectory()) {
                    if (Pattern.matches(regularExpressionForNextFolder, childFile.getName())) {
                        matchingFiles.add(childFile);
                    }
                }
            }
            if (matchingFiles.size() == 1) {
                currentDirectory = matchingFiles.get(0);
            } else if (matchingFiles.size() == 0) {
                throw new IllegalStateException("Unable to locate a sub folder matching the regular expression["
                        + regularExpressionForNextFolder + "] in the directory["
                        + currentDirectory.getAbsolutePath() + "].");
            } else {
                throw new IllegalStateException("The regular expression[" + regularExpressionForNextFolder
                        + "] matches more than one file (" + matchingFiles.size()
                        + " matches found) in the directory[" + currentDirectory.getAbsolutePath() + "].");
            }
        }
    }

    return currentDirectory;
}