Example usage for java.util.regex Matcher find

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

Introduction

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

Prototype

public boolean find() 

Source Link

Document

Attempts to find the next subsequence of the input sequence that matches the pattern.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    Pattern p = Pattern.compile("^java", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    Matcher m = p.matcher("java has regex\nJava has regex\n" + "JAVA has pretty good regular expressions\n"
            + "Regular expressions are in Java");
    while (m.find())
        System.out.println(m.group());
}

From source file:TheReplacements.java

public static void main(String[] args) throws Exception {
    String s = TextFile.read("TheReplacements.java");
    // Match the specially-commented block of text above:
    Matcher mInput = Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
    if (mInput.find())
        s = mInput.group(1); // Captured by parentheses
    // Replace two or more spaces with a single space:
    s = s.replaceAll(" {2,}", " ");
    // Replace one or more spaces at the beginning of each
    // line with no spaces. Must enable MULTILINE mode:
    s = s.replaceAll("(?m)^ +", "");
    System.out.println(s);/*from  ww  w  .jav a2s.  c  o m*/
    s = s.replaceFirst("[aeiou]", "(VOWEL1)");
    StringBuffer sbuf = new StringBuffer();
    Pattern p = Pattern.compile("[aeiou]");
    Matcher m = p.matcher(s);
    // Process the find information as you
    // perform the replacements:
    while (m.find())
        m.appendReplacement(sbuf, m.group().toUpperCase());
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    System.out.println(sbuf);

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String filename = "infile.txt";
    String patternStr = "pattern";
    BufferedReader rd = new BufferedReader(new FileReader(filename));

    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher("\\D");

    String line = null;/*  w w w .  j  a va 2s.c  o  m*/
    while ((line = rd.readLine()) != null) {
        matcher.reset(line);
        if (matcher.find()) {
            // line matches the pattern
        }
    }
}

From source file:BookRank.java

/** Grab the sales rank off the web page and log it. */
public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    String title = p.getProperty("title", "NO TITLE IN PROPERTIES");
    // The url must have the "isbn=" at the very end, or otherwise
    // be amenable to being string-catted to, like the default.
    String url = p.getProperty("url", "http://test.ing/test.cgi?isbn=");
    // The 10-digit ISBN for the book.
    String isbn = p.getProperty("isbn", "0000000000");
    // The RE pattern (MUST have ONE capture group for the number)
    String pattern = p.getProperty("pattern", "Rank: (\\d+)");

    // Looking for something like this in the input:
    //    <b>QuickBookShop.web Sales Rank: </b>
    //    26,252//from  w w w  .  j a  va  2  s .  com
    //    </font><br>

    Pattern r = Pattern.compile(pattern);

    // Open the URL and get a Reader from it.
    BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream()));
    // Read the URL looking for the rank information, as
    // a single long string, so can match RE across multi-lines.
    String input = "input from console";
    // System.out.println(input);

    // If found, append to sales data file.
    Matcher m = r.matcher(input);
    if (m.find()) {
        PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true));
        String date = // `date +'%m %d %H %M %S %Y'`;
                new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date());
        // Paren 1 is the digits (and maybe ','s) that matched; remove comma
        Matcher noComma = Pattern.compile(",").matcher(m.group(1));
        pw.println(date + noComma.replaceAll(""));
        pw.close();
    } else {
        System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!");
    }

    // Whether current data found or not, draw the graph, using
    // external plotting program against all historical data.
    // Could use gnuplot, R, any other math/graph program.
    // Better yet: use one of the Java plotting APIs.

    String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n"
            + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n"
            + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE
            + "\" using 1:7 title \"" + title + "\" with lines\n";

    Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot");
    PrintWriter gp = new PrintWriter(proc.getOutputStream());
    gp.print(gnuplot_cmd);
    gp.close();
}

From source file:musiccrawler.MusicCrawler.java

public static void main(String[] args) {
    String test = "\"Yeu";
    String regex = "^\"|\"$";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(test);
    System.out.println(test);//from www.j ava2s . c  om
    if (m.find()) {
        System.out.println(test.replaceAll(regex, ""));
    }
}

From source file:FindA.java

public static void main(String args[]) throws Exception {

    String candidate = "A Matcher examines the results of applying a pattern.";

    String regex = "\\ba\\w*\\b";
    Pattern p = Pattern.compile(regex);

    Matcher m = p.matcher(candidate);
    String val = null;
    System.out.println("INPUT: " + candidate);

    System.out.println("REGEX: " + regex + "\r\n");

    while (m.find()) {
        val = m.group();
        System.out.println("MATCH: " + val);
    }//w  w w.  ja v  a 2  s  .co m
    if (val == null) {
        System.out.println("NO MATCHES: ");
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {

    String candidate = "this is a test, A TEST.";

    String regex = "\\ba\\w*\\b";
    Pattern p = Pattern.compile(regex);

    Matcher m = p.matcher(candidate);
    String val = null;
    System.out.println("INPUT: " + candidate);

    System.out.println("REGEX: " + regex + "\r\n");

    while (m.find()) {
        val = m.group();
        System.out.println("MATCH: " + val);
    }/* ww w. j av a  2 s . co m*/

    if (val == null) {
        System.out.println("NO MATCHES: ");
    }
}

From source file:Grep0.java

public static void main(String[] args) throws IOException {
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    if (args.length != 1) {
        System.err.println("Usage: MatchLines pattern");
        System.exit(1);//from   w  ww  .  java2s .  c  om
    }
    Pattern patt = Pattern.compile(args[0]);
    Matcher matcher = patt.matcher("");
    String line = null;
    while ((line = is.readLine()) != null) {
        matcher.reset(line);
        if (matcher.find()) {
            System.out.println("MATCH: " + line);
        }
    }
}

From source file:com.adobe.aem.demomachine.RegExp.java

public static void main(String[] args) throws IOException {

    String fileName = null;//w ww . j  ava 2  s .c  o  m
    String regExp = null;
    String position = null;
    String value = "n/a";
    List<String> allMatches = new ArrayList<String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Filename");
    options.addOption("r", true, "RegExp");
    options.addOption("p", true, "Position");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            fileName = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("f")) {
            regExp = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("p")) {
            position = cmd.getOptionValue("p");
        }

        if (fileName == null || regExp == null || position == null) {
            System.out.println("Command line parameters: -f fileName -r regExp -p position");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    String content = readFile(fileName, Charset.defaultCharset());

    if (content != null) {
        Matcher m = Pattern.compile(regExp).matcher(content);
        while (m.find()) {
            String group = m.group();
            int pos = group.indexOf(".zip");
            if (pos > 0) {
                group = group.substring(0, pos);
            }
            logger.debug("RegExp: " + m.group() + " found returning " + group);
            allMatches.add(group);
        }

        if (allMatches.size() > 0) {

            if (position.equals("first")) {
                value = allMatches.get(0);
            }

            if (position.equals("last")) {
                value = allMatches.get(allMatches.size() - 1);
            }
        }
    }

    System.out.println(value);

}

From source file:com.github.xbn.examples.regexutil.non_xbn.MatchEachWordInEveryLine.java

public static final void main(String[] as_1RqdTxtFilePath) {
    Iterator<String> lineItr = null;
    try {/*w w w  .j ava  2  s .com*/
        lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null
    } catch (IOException iox) {
        throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox);
    } catch (RuntimeException rx) {
        throw new RuntimeException("One required parameter: The path to the text file.", rx);
    }

    //Dummy search string (""), so it can be reused (reset)
    Matcher mWord = Pattern.compile("\\b\\w+\\b").matcher("");
    while (lineItr.hasNext()) {
        String sLine = lineItr.next();
        mWord.reset(sLine);
        while (mWord.find()) {
            System.out.println(mWord.group());
        }
    }

}