Search in sources :

Example 71 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project ASCIIGenome by dariober.

the class TrackSet method setFeatureColorForRegex.

public void setFeatureColorForRegex(List<String> cmdTokens) throws InvalidCommandLineException, InvalidColourException {
    List<String> argList = new ArrayList<String>(cmdTokens);
    // Remove cmd name
    argList.remove(0);
    // Collect all regex/color pairs from input. We move left to right along the command
    // arguments and collect -r/-R and set the regex inversion accordingly.
    List<Argument> colorForRegex = new ArrayList<Argument>();
    new Xterm256();
    while (argList.contains("-r") || argList.contains("-R")) {
        int r = argList.indexOf("-r") >= 0 ? argList.indexOf("-r") : Integer.MAX_VALUE;
        int R = argList.indexOf("-R") >= 0 ? argList.indexOf("-R") : Integer.MAX_VALUE;
        List<String> pair;
        boolean invert = false;
        if (r < R) {
            pair = Utils.getNArgsForParam(argList, "-r", 2);
        } else {
            pair = Utils.getNArgsForParam(argList, "-R", 2);
            invert = true;
        }
        String pattern = pair.get(0);
        try {
            // Check valid regex
            Pattern.compile(pattern);
        } catch (PatternSyntaxException e) {
            System.err.println("Invalid regex: " + pattern);
            throw new InvalidCommandLineException();
        }
        Argument xcolor = new Argument(pair.get(0), pair.get(1), invert);
        // Check this is a valid colour
        Xterm256.colorNameToXterm256(xcolor.getArg());
        colorForRegex.add(xcolor);
    }
    if (colorForRegex.size() == 0) {
        colorForRegex = null;
    }
    boolean invertSelection = Utils.argListContainsFlag(argList, "-v");
    // Regex to capture tracks: All positional args left
    List<String> trackNameRegex = new ArrayList<String>();
    if (argList.size() > 0) {
        trackNameRegex = argList;
    } else {
        // Default: Capture everything
        trackNameRegex.add(".*");
    }
    // Set as appropriate
    List<Track> tracksToReset = this.matchTracks(trackNameRegex, true, invertSelection);
    for (Track tr : tracksToReset) {
        tr.setColorForRegex(colorForRegex);
    }
}
Also used : Xterm256(coloring.Xterm256) ArrayList(java.util.ArrayList) InvalidCommandLineException(exceptions.InvalidCommandLineException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 72 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project ASCIIGenome by dariober.

the class TrackSet method setFilterForTrackIntervalFeature.

/**
 * Set filter for IntervalFeature tracks.
 * @throws SQLException
 * @throws InvalidRecordException
 * @throws InvalidGenomicCoordsException
 * @throws IOException
 * @throws ClassNotFoundException
 */
public void setFilterForTrackIntervalFeature(List<String> cmdInput) throws InvalidCommandLineException, ClassNotFoundException, IOException, InvalidGenomicCoordsException, InvalidRecordException, SQLException {
    List<String> args = new ArrayList<String>();
    for (String x : cmdInput) {
        args.add(x);
    }
    // Remove command name
    args.remove(0);
    // Default
    Pattern showRegex = Pattern.compile(Filter.DEFAULT_SHOW_REGEX.getValue());
    Pattern hideRegex = Pattern.compile(Filter.DEFAULT_HIDE_REGEX.getValue());
    // Get args:
    boolean invertSelection = Utils.argListContainsFlag(args, "-v");
    int flag = 0;
    if (Utils.argListContainsFlag(args, "-F")) {
        flag |= Pattern.LITERAL;
    }
    if (!Utils.argListContainsFlag(args, "-c")) {
        flag |= Pattern.CASE_INSENSITIVE;
    }
    try {
        if (args.contains("-i")) {
            int idx = args.indexOf("-i") + 1;
            showRegex = Pattern.compile(args.get(idx), flag);
            args.remove(idx);
            args.remove("-i");
        }
        if (args.contains("-e")) {
            int idx = args.indexOf("-e") + 1;
            hideRegex = Pattern.compile(args.get(idx), flag);
            args.remove(idx);
            args.remove("-e");
        }
    } catch (PatternSyntaxException e) {
        System.err.println("Invalid regex");
        throw new InvalidCommandLineException();
    }
    // What is left is positional args of regexes
    List<String> trackNameRegex = new ArrayList<String>();
    trackNameRegex.addAll(args);
    if (trackNameRegex.size() == 0) {
        // Default regex for matching tracks
        trackNameRegex.add(".*");
    }
    // TRACK REGEXES
    // Regex
    // And set as required:
    List<Track> tracksToReset = this.matchTracks(trackNameRegex, true, invertSelection);
    for (Track tr : tracksToReset) {
        tr.setShowHideRegex(showRegex, hideRegex);
    }
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) InvalidCommandLineException(exceptions.InvalidCommandLineException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 73 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project SeqMonk by s-andrews.

the class DataSetEditor method actionPerformed.

/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
public void actionPerformed(ActionEvent ae) {
    String c = ae.getActionCommand();
    if (c.equals("rename_dataset")) {
        DataSet s = (DataSet) dataSetList.getSelectedValue();
        String dataSetName = null;
        while (true) {
            dataSetName = (String) JOptionPane.showInputDialog(this, "Enter DataSet name", "DataSet Name", JOptionPane.QUESTION_MESSAGE, null, null, s.name());
            // They cancelled
            if (dataSetName == null)
                return;
            if (dataSetName.length() > 0)
                break;
        }
        s.setName(dataSetName);
        dataSetModel.setElementAt(s, dataSetList.getSelectedIndex());
    } else if (c.equals("replace")) {
        Object[] o = dataSetList.getSelectedValues();
        DataSet[] ds = new DataSet[o.length];
        for (int i = 0; i < o.length; i++) {
            ds[i] = (DataSet) o[i];
        }
        String replaceWhat = null;
        while (true) {
            replaceWhat = (String) JOptionPane.showInputDialog(this, "Replace what", "Replace text", JOptionPane.QUESTION_MESSAGE, null, null, "");
            // They cancelled
            if (replaceWhat == null)
                return;
            if (replaceWhat.length() > 0)
                break;
        }
        String replaceWith = (String) JOptionPane.showInputDialog(this, "Replace with", "Replace text", JOptionPane.QUESTION_MESSAGE, null, null, "");
        // They cancelled
        if (replaceWith == null)
            return;
        // catch this so as to produce a nicer error message
        try {
            for (int s = 0; s < ds.length; s++) {
                String oldName = ds[s].name();
                String newName = oldName.replaceAll(replaceWhat, replaceWith);
                ds[s].setName(newName);
            }
            ListDataListener[] l = dataSetModel.getListDataListeners();
            for (int i = 0; i < l.length; i++) {
                l[i].contentsChanged(new ListDataEvent(dataSetModel, ListDataEvent.CONTENTS_CHANGED, 0, ds.length));
            }
        } catch (PatternSyntaxException pse) {
            JOptionPane.showMessageDialog(this, "<html>You used a regex in your search, but it contained a syntax error<br><br>" + pse.getLocalizedMessage(), "Pattern error", JOptionPane.ERROR_MESSAGE);
        }
    } else if (c.equals("reset")) {
        Object[] o = dataSetList.getSelectedValues();
        if (JOptionPane.showConfirmDialog(this, "Reset names to original file names?", "Reset names?", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
            return;
        for (int i = 0; i < o.length; i++) {
            DataSet d = (DataSet) o[i];
            File f = new File(d.fileName());
            d.setName(f.getName());
        }
    } else if (c.equals("select_names")) {
        // We need to collect a list of names we want to keep
        CollectDataSetNamesDialog d = new CollectDataSetNamesDialog();
        String[] names = d.getNames();
        System.err.println("Got a list of " + names.length + " names");
        // They cancelled or didn't enter anything
        if (names.length == 0)
            return;
        IntVector iv = new IntVector();
        INDEX: for (int index = 0; index < dataSetModel.getSize(); index++) {
            for (int n = 0; n < names.length; n++) {
                if (names[n].equals(dataSetModel.elementAt(index).toString())) {
                    // System.err.println("It matches");
                    iv.add(index);
                    continue INDEX;
                }
            }
        }
        dataSetList.setSelectedIndices(iv.toArray());
    } else if (c.equals("close")) {
        setVisible(false);
        dispose();
    } else if (c.equals("delete_dataset")) {
        Object[] o = dataSetList.getSelectedValues();
        if (JOptionPane.showConfirmDialog(this, "Are you sure you want to delete " + o.length + " data sets?", "Really delete?", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
            return;
        DataSet[] ds = new DataSet[o.length];
        for (int i = 0; i < o.length; i++) {
            ds[i] = (DataSet) o[i];
            dataSetModel.removeElement(o[i]);
        }
        collection.removeDataSets(ds);
    } else if (c.equals("close")) {
        setVisible(false);
        dispose();
    }
}
Also used : ListDataEvent(javax.swing.event.ListDataEvent) IntVector(uk.ac.babraham.SeqMonk.Utilities.IntVector) DataSet(uk.ac.babraham.SeqMonk.DataTypes.DataSet) File(java.io.File) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 74 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project incubator-weex by apache.

the class AbstractEditComponent method parseToPattern.

private PatternWrapper parseToPattern(String jsPattern, String replace) {
    if (jsPattern == null || replace == null) {
        return null;
    }
    String checker = "/[\\S]+/[i]?[m]?[g]?";
    if (!Pattern.compile(checker).matcher(jsPattern).matches()) {
        WXLogUtils.w("WXInput", "Illegal js pattern syntax: " + jsPattern);
        return null;
    }
    int flags = 0;
    boolean global = false;
    String flagsStr = jsPattern.substring(jsPattern.lastIndexOf("/") + 1);
    String regExp = jsPattern.substring(jsPattern.indexOf("/") + 1, jsPattern.lastIndexOf("/"));
    if (flagsStr.contains("i")) {
        flags |= Pattern.CASE_INSENSITIVE;
    }
    if (flagsStr.contains("m")) {
        flags |= Pattern.DOTALL;
    }
    if (flagsStr.contains("g")) {
        global = true;
    }
    Pattern pattern = null;
    try {
        pattern = Pattern.compile(regExp, flags);
    } catch (PatternSyntaxException e) {
        WXLogUtils.w("WXInput", "Pattern syntax error: " + regExp);
    }
    if (pattern == null) {
        return null;
    }
    PatternWrapper wrapper = new PatternWrapper();
    wrapper.global = global;
    wrapper.matcher = pattern;
    wrapper.replace = replace;
    return wrapper;
}
Also used : Pattern(java.util.regex.Pattern) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 75 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project beast2 by CompEvol.

the class GuessPatternDialog method showDialog.

public Status showDialog(String title) {
    JOptionPane optionPane = new JOptionPane(guessPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, new String[] { "Cancel", "OK" }, "OK");
    optionPane.setBorder(new EmptyBorder(12, 12, 12, 12));
    final JDialog dialog = optionPane.createDialog(m_parent, title);
    dialog.setName("GuessTaxonSets");
    // dialog.setResizable(true);
    dialog.pack();
    updateFields();
    dialog.setVisible(true);
    if (optionPane.getValue() == null || !optionPane.getValue().equals("OK")) {
        return Status.canceled;
    }
    if (useEverything.getModel() == group.getSelection()) {
        String delimiter = normalise(textSplitChar.getText());
        switch(m_location) {
            case // "after first",
            0:
                pattern = "^[^" + delimiter + "]+" + delimiter + "(.*)$";
                break;
            case // "after last",
            1:
                pattern = "^.*" + delimiter + "(.*)$";
                break;
            case // "before first",
            2:
                pattern = "^([^" + delimiter + "]+)" + delimiter + ".*$";
                break;
            case // "before last"
            3:
                pattern = "^(.*)" + delimiter + ".*$";
                break;
        }
    }
    if (isSplitOnChar.getModel() == group.getSelection()) {
        String delimiter = normalise(textSplitChar2.getText());
        switch(m_splitlocation) {
            case // "1"
            0:
                pattern = "^([^" + delimiter + "]+)" + ".*$";
                break;
            case // "2"
            1:
                pattern = "^[^" + delimiter + "]+" + delimiter + "([^" + delimiter + "]+)" + ".*$";
                break;
            case // "3"
            2:
                pattern = "^[^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+" + delimiter + "([^" + delimiter + "]+)" + ".*$";
                break;
            case // "4"
            3:
                pattern = "^[^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+" + delimiter + "([^" + delimiter + "]+)" + ".*$";
                break;
            case // "1-2"
            4:
                pattern = "^([^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+)" + ".*$";
                break;
            case // "2-3"
            5:
                pattern = "^[^" + delimiter + "]+" + delimiter + "([^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+)" + ".*$";
                break;
            case // "3-4"
            6:
                pattern = "^[^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+" + delimiter + "([^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+)" + ".*$";
                break;
            case // "1-3"
            7:
                pattern = "^([^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+)" + ".*$";
                break;
            case // "2-4"
            8:
                pattern = "^[^" + delimiter + "]+" + delimiter + "([^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+" + delimiter + "[^" + delimiter + "]+)" + ".*$";
        }
    }
    if (useRegexp.getModel() == group.getSelection()) {
        pattern = textRegExp.getText();
    }
    if (readFromFile.getModel() == group.getSelection()) {
        try {
            BufferedReader fin = new BufferedReader(new FileReader(txtFile.getText()));
            StringBuffer buf = new StringBuffer();
            // process data
            while (fin.ready()) {
                String str = fin.readLine();
                str = str.replaceFirst("\t", "=") + ",";
                // only add entries that are non-empty
                if (str.indexOf("=") > 0 && !str.matches("^\\s+=.*$")) {
                    buf.append(str);
                }
            }
            fin.close();
            trait = buf.toString().trim();
            while (trait.endsWith(",")) {
                trait = trait.substring(0, trait.length() - 1).trim();
            }
            if (trait.trim().length() == 0) {
                JOptionPane.showMessageDialog(m_parent, "Could not find trait information in the file. " + "Perhaps this is not a tab-delimited but space file?");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(m_parent, "Loading trait from file failed:" + e.getMessage());
            return Status.canceled;
        }
        return Status.trait;
    }
    // sanity check
    try {
        pattern.matches(pattern);
    } catch (PatternSyntaxException e) {
        JOptionPane.showMessageDialog(this, "This is not a valid regular expression");
        return Status.canceled;
    }
    if (optionPane.getValue() != null && optionPane.getValue().equals("OK")) {
        Log.warning.println("Pattern = " + pattern);
        return Status.pattern;
    } else {
        return Status.canceled;
    }
}
Also used : BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) EmptyBorder(javax.swing.border.EmptyBorder) JOptionPane(javax.swing.JOptionPane) JDialog(javax.swing.JDialog) PatternSyntaxException(java.util.regex.PatternSyntaxException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

PatternSyntaxException (java.util.regex.PatternSyntaxException)355 Pattern (java.util.regex.Pattern)190 Matcher (java.util.regex.Matcher)115 ArrayList (java.util.ArrayList)46 IOException (java.io.IOException)25 List (java.util.List)19 File (java.io.File)14 Map (java.util.Map)12 HashMap (java.util.HashMap)9 URL (java.net.URL)7 HashSet (java.util.HashSet)7 Iterator (java.util.Iterator)7 InvalidSettingsException (org.knime.core.node.InvalidSettingsException)7 BufferedReader (java.io.BufferedReader)6 Collection (java.util.Collection)6 LinkedList (java.util.LinkedList)5 Test (org.junit.Test)5 InputStreamReader (java.io.InputStreamReader)4 SQLException (java.sql.SQLException)4 LinkedHashMap (java.util.LinkedHashMap)4