Example usage for java.util.regex Matcher start

List of usage examples for java.util.regex Matcher start

Introduction

In this page you can find the example usage for java.util.regex Matcher start.

Prototype

public int start() 

Source Link

Document

Returns the start index of the previous match.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    String[] input = new String[] { "Java has regular expressions in 1.4",
            "regular expressions now expressing in Java", "Java represses oracular expressions" };

    Pattern p1 = Pattern.compile("re\\w*"), p2 = Pattern.compile("Java.*");

    for (int i = 0; i < input.length; i++) {
        System.out.println("input " + i + ": " + input[i]);
        Matcher m1 = p1.matcher(input[i]), m2 = p2.matcher(input[i]);
        while (m1.find())
            System.out.println("m1.find() '" + m1.group() + "' start = " + m1.start() + " end = " + m1.end());
    }//from   w w w.  ja  v  a2s.  com
}

From source file:HrefMatch.java

public static void main(String[] args) {
    try {/*  w w w  . j  a  v a  2 s.c  om*/
        // get URL string from command line or use default
        String urlString;
        if (args.length > 0)
            urlString = args[0];
        else
            urlString = "http://java.sun.com";

        // open reader for URL
        InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());

        // read contents into string builder
        StringBuilder input = new StringBuilder();
        int ch;
        while ((ch = in.read()) != -1)
            input.append((char) ch);

        // search for all occurrences of pattern
        String patternString = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>]*)\\s*>";
        Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String match = input.substring(start, end);
            System.out.println(match);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (PatternSyntaxException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    String[] input = new String[] { "Java has regular expressions in 1.4",
            "regular expressions now expressing in Java", "Java represses oracular expressions" };

    Pattern p1 = Pattern.compile("re\\w*"), p2 = Pattern.compile("Java.*");

    for (int i = 0; i < input.length; i++) {
        System.out.println("input " + i + ": " + input[i]);
        Matcher m1 = p1.matcher(input[i]), m2 = p2.matcher(input[i]);
        if (m1.lookingAt()) // No reset() necessary
            System.out.println("m1.lookingAt() start = " + m1.start() + " end = " + m1.end());

    }//from  ww  w.  ja  va  2  s. c  o m
}

From source file:StartEnd.java

public static void main(String[] args) {
    String[] input = new String[] { "Java has regular expressions in 1.4",
            "regular expressions now expressing in Java", "Java represses oracular expressions" };
    Pattern p1 = Pattern.compile("re\\w*"), p2 = Pattern.compile("Java.*");
    for (int i = 0; i < input.length; i++) {
        System.out.println("input " + i + ": " + input[i]);
        Matcher m1 = p1.matcher(input[i]), m2 = p2.matcher(input[i]);
        while (m1.find())
            System.out.println("m1.find() '" + m1.group() + "' start = " + m1.start() + " end = " + m1.end());
        while (m2.find())
            System.out.println("m2.find() '" + m2.group() + "' start = " + m2.start() + " end = " + m2.end());
        if (m1.lookingAt()) // No reset() necessary
            System.out.println("m1.lookingAt() start = " + m1.start() + " end = " + m1.end());
        if (m2.lookingAt())
            System.out.println("m2.lookingAt() start = " + m2.start() + " end = " + m2.end());
        if (m1.matches()) // No reset() necessary
            System.out.println("m1.matches() start = " + m1.start() + " end = " + m1.end());
        if (m2.matches())
            System.out.println("m2.matches() start = " + m2.start() + " end = " + m2.end());
    }/*from  w  w  w .j a  v  a  2 s  .c om*/
}

From source file:Main.java

public static void main(String[] args) {
    String patternStr = "b";
    Pattern pattern = Pattern.compile(patternStr);

    CharSequence inputStr = "a b c b";
    Matcher matcher = pattern.matcher(inputStr);
    boolean matchFound = matcher.find();
    System.out.println(matchFound);

    String match = matcher.group();
    System.out.println(match);//from   ww  w .j  av a 2 s .c o m

    int start = matcher.start();
    int end = matcher.end();
    System.out.println(start);
    System.out.println(end);
    matchFound = matcher.find();
}

From source file:MatcherDemo.java

public static void main(String[] args) {
    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(INPUT); // get a matcher object
    int count = 0;
    while (m.find()) {
        count++;// w w w . jav a  2s .  c om
        System.out.println("Match number " + count);
        System.out.println("start(): " + m.start());
        System.out.println("end(): " + m.end());
    }
}

From source file:MatcherTest.java

public static void main(String[] argv) {
    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(INPUT); // get a matcher object
    int count = 0;
    while (m.find()) {
        count++;//from  ww  w  . j ava 2  s  . c om
        System.out.println("Match number " + count);
        System.out.println("start(): " + m.start());
        System.out.println("end(): " + m.end());
    }
}

From source file:com.gzj.tulip.jade.statement.SystemInterpreter.java

public static void main(String[] args) throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("table", "my_table_name");
    parameters.put("id", "my_id");
    parameters.put(":1", "first_param");

    final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)");

    String sql = "select form ##(:table) {name} where {id}='{1}'";

    StringBuilder sb = new StringBuilder(sql.length() + 200);
    Matcher matcher = PATTERN.matcher(sql);
    int start = 0;
    while (matcher.find(start)) {
        sb.append(sql.substring(start, matcher.start()));
        String group = matcher.group();
        String key = null;/*from   w w  w  .  ja v  a 2s . c o m*/
        if (group.startsWith("{")) {
            key = matcher.group(1);
        } else if (group.startsWith("##(")) {
            key = matcher.group(2);
        }
        System.out.println(key);
        if (key == null || key.length() == 0) {
            continue;
        }
        Object value = parameters.get(key); // {paramName}?{:1}?
        if (value == null) {
            if (key.startsWith(":") || key.startsWith("$")) {
                value = parameters.get(key.substring(1)); // {:paramName}
            } else {
                char ch = key.charAt(0);
                if (ch >= '0' && ch <= '9') {
                    value = parameters.get(":" + key); // {1}?
                }
            }
        }
        if (value == null) {
            value = parameters.get(key); // ?
        }
        if (value != null) {
            sb.append(value);
        } else {
            sb.append(group);
        }
        start = matcher.end();
    }
    sb.append(sql.substring(start));
    System.out.println(sb);

}

From source file:BGrep.java

public static void main(String[] args) {
    String encodingName = "UTF-8"; // Default to UTF-8 encoding
    int flags = Pattern.MULTILINE; // Default regexp flags

    try { // Fatal exceptions are handled after this try block
        // First, process any options
        int nextarg = 0;
        while (args[nextarg].charAt(0) == '-') {
            String option = args[nextarg++];
            if (option.equals("-e")) {
                encodingName = args[nextarg++];
            } else if (option.equals("-i")) { // case-insensitive matching
                flags |= Pattern.CASE_INSENSITIVE;
            } else if (option.equals("-s")) { // Strict Unicode processing
                flags |= Pattern.UNICODE_CASE; // case-insensitive Unicode
                flags |= Pattern.CANON_EQ; // canonicalize Unicode
            } else {
                System.err.println("Unknown option: " + option);
                usage();//w  w  w  . j a v a 2 s .co m
            }
        }

        // Get the Charset for converting bytes to chars
        Charset charset = Charset.forName(encodingName);

        // Next argument must be a regexp. Compile it to a Pattern object
        Pattern pattern = Pattern.compile(args[nextarg++], flags);

        // Require that at least one file is specified
        if (nextarg == args.length)
            usage();

        // Loop through each of the specified filenames
        while (nextarg < args.length) {
            String filename = args[nextarg++];
            CharBuffer chars; // This will hold complete text of the file
            try { // Handle per-file errors locally
                // Open a FileChannel to the named file
                FileInputStream stream = new FileInputStream(filename);
                FileChannel f = stream.getChannel();

                // Memory-map the file into one big ByteBuffer. This is
                // easy but may be somewhat inefficient for short files.
                ByteBuffer bytes = f.map(FileChannel.MapMode.READ_ONLY, 0, f.size());

                // We can close the file once it is is mapped into memory.
                // Closing the stream closes the channel, too.
                stream.close();

                // Decode the entire ByteBuffer into one big CharBuffer
                chars = charset.decode(bytes);
            } catch (IOException e) { // File not found or other problem
                System.err.println(e); // Print error message
                continue; // and move on to the next file
            }

            // This is the basic regexp loop for finding all matches in a
            // CharSequence. Note that CharBuffer implements CharSequence.
            // A Matcher holds state for a given Pattern and text.
            Matcher matcher = pattern.matcher(chars);
            while (matcher.find()) { // While there are more matches
                // Print out details of the match
                System.out.println(filename + ":" + // file name
                        matcher.start() + ": " + // character pos
                        matcher.group()); // matching text
            }
        }
    }
    // These are the things that can go wrong in the code above
    catch (UnsupportedCharsetException e) { // Bad encoding name
        System.err.println("Unknown encoding: " + encodingName);
    } catch (PatternSyntaxException e) { // Bad pattern
        System.err.println("Syntax error in search pattern:\n" + e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e) { // Wrong number of arguments
        usage();
    }
}

From source file:it.unipd.dei.ims.falcon.CmdLine.java

public static void main(String[] args) {

    // last argument is always index path
    Options options = new Options();
    // one of these actions has to be specified
    OptionGroup actionGroup = new OptionGroup();
    actionGroup.addOption(new Option("i", true, "perform indexing")); // if dir, all files, else only one file
    actionGroup.addOption(new Option("q", true, "perform a single query"));
    actionGroup.addOption(new Option("b", false, "perform a query batch (read from stdin)"));
    actionGroup.setRequired(true);/* w  w w . j a va 2  s .co  m*/
    options.addOptionGroup(actionGroup);

    // other options
    options.addOption(new Option("l", "segment-length", true, "length of a segment (# of chroma vectors)"));
    options.addOption(
            new Option("o", "segment-overlap", true, "overlap portion of a segment (# of chroma vectors)"));
    options.addOption(new Option("Q", "quantization-level", true, "quantization level for chroma vectors"));
    options.addOption(new Option("k", "min-kurtosis", true, "minimum kurtosis for indexing chroma vectors"));
    options.addOption(new Option("s", "sub-sampling", true, "sub-sampling of chroma features"));
    options.addOption(new Option("v", "verbose", false, "verbose output (including timing info)"));
    options.addOption(new Option("T", "transposition-estimator-strategy", true,
            "parametrization for the transposition estimator strategy"));
    options.addOption(new Option("t", "n-transp", true,
            "number of transposition; if not specified, no transposition is performed"));
    options.addOption(new Option("f", "force-transp", true, "force transposition by an amount of semitones"));
    options.addOption(new Option("p", "pruning", false,
            "enable query pruning; if -P is unspecified, use default strategy"));
    options.addOption(new Option("P", "pruning-custom", true, "custom query pruning strategy"));

    // parse
    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length != 1)
            throw new ParseException("no index path was specified");
    } catch (ParseException ex) {
        System.err.println("ERROR - parsing command line:");
        System.err.println(ex.getMessage());
        formatter.printHelp("falcon -{i,q,b} [options] index_path", options);
        return;
    }

    // default values
    final float[] DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY = new float[] { 0.65192807f, 0.0f, 0.0f, 0.0f,
            0.3532628f, 0.4997167f, 0.0f, 0.41703504f, 0.0f, 0.16297342f, 0.0f, 0.0f };
    final String DEFAULT_QUERY_PRUNING_STRATEGY = "ntf:0.340765*[0.001694,0.995720];ndf:0.344143*[0.007224,0.997113];"
            + "ncf:0.338766*[0.001601,0.995038];nmf:0.331577*[0.002352,0.997884];"; // TODO not the final one

    int hashes_per_segment = Integer.parseInt(cmd.getOptionValue("l", "150"));
    int overlap_per_segment = Integer.parseInt(cmd.getOptionValue("o", "50"));
    int nranks = Integer.parseInt(cmd.getOptionValue("Q", "3"));
    int subsampling = Integer.parseInt(cmd.getOptionValue("s", "1"));
    double minkurtosis = Float.parseFloat(cmd.getOptionValue("k", "-100."));
    boolean verbose = cmd.hasOption("v");
    int ntransp = Integer.parseInt(cmd.getOptionValue("t", "1"));
    TranspositionEstimator tpe = null;
    if (cmd.hasOption("t")) {
        if (cmd.hasOption("T")) {
            // TODO this if branch is yet to test
            Pattern p = Pattern.compile("\\d\\.\\d*");
            LinkedList<Double> tokens = new LinkedList<Double>();
            Matcher m = p.matcher(cmd.getOptionValue("T"));
            while (m.find())
                tokens.addLast(new Double(cmd.getOptionValue("T").substring(m.start(), m.end())));
            float[] strategy = new float[tokens.size()];
            if (strategy.length != 12) {
                System.err.println("invalid transposition estimator strategy");
                System.exit(1);
            }
            for (int i = 0; i < strategy.length; i++)
                strategy[i] = new Float(tokens.pollFirst());
        } else {
            tpe = new TranspositionEstimator(DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY);
        }
    } else if (cmd.hasOption("f")) {
        int[] transps = parseIntArray(cmd.getOptionValue("f"));
        tpe = new ForcedTranspositionEstimator(transps);
        ntransp = transps.length;
    }
    QueryPruningStrategy qpe = null;
    if (cmd.hasOption("p")) {
        if (cmd.hasOption("P")) {
            qpe = new StaticQueryPruningStrategy(cmd.getOptionValue("P"));
        } else {
            qpe = new StaticQueryPruningStrategy(DEFAULT_QUERY_PRUNING_STRATEGY);
        }
    }

    // action
    if (cmd.hasOption("i")) {
        try {
            Indexing.index(new File(cmd.getOptionValue("i")), new File(cmd.getArgs()[0]), hashes_per_segment,
                    overlap_per_segment, subsampling, nranks, minkurtosis, tpe, verbose);
        } catch (IndexingException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (cmd.hasOption("q")) {
        String queryfilepath = cmd.getOptionValue("q");
        doQuery(cmd, queryfilepath, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp,
                minkurtosis, qpe, verbose);
    }
    if (cmd.hasOption("b")) {
        try {
            long starttime = System.currentTimeMillis();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while ((line = in.readLine()) != null && !line.trim().isEmpty())
                doQuery(cmd, line, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp,
                        minkurtosis, qpe, verbose);
            in.close();
            long endtime = System.currentTimeMillis();
            System.out.println(String.format("total time: %ds", (endtime - starttime) / 1000));
        } catch (IOException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}