Example usage for java.util.regex Pattern matcher

List of usage examples for java.util.regex Pattern matcher

Introduction

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

Prototype

public Matcher matcher(CharSequence input) 

Source Link

Document

Creates a matcher that will match the given input against this pattern.

Usage

From source file:net.cliftonsnyder.svgchart.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")");
    options.addOption("h", "height", true, "chart height");
    options.addOption("i", "input-file", true, "input file [default: stdin]");
    options.addOption("o", "output-file", true, "output file [default: stdout]");
    options.addOption("w", "width", true, "chart width");
    options.addOption("?", "help", false, "print a brief help message");

    Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES));
    type.setRequired(true);//  www .j  a v a 2 s. c om
    options.addOption(type);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            formatter.printHelp(USAGE, options);
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("unable to parse command line: " + exp.getMessage());
        formatter.printHelp(USAGE, options);
        System.exit(1);
    }

    SVGChart chart = null;
    String tmp = line.getOptionValue("type");
    Matcher m = null;
    for (Pattern p : SVGChart.TYPE_PATTERNS) {
        if ((m = p.matcher(tmp)).matches()) {
            switch (m.group().charAt(0)) {
            case 'l':
                // DEBUG
                System.err.println("line");
                break;
            case 'b':
                System.err.println("bar");
                chart = new BarChart();
                break;
            case 'p':
                System.err.println("pie");
                break;
            default:
                System.err.println("unknown or unimplemented chart type: '" + tmp + "'");
                System.exit(1);
            }
        }
    }

    try {
        chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'");
        System.exit(1);
    }

    try {
        chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'");
        System.exit(1);
    }

    InputStream in = System.in;
    tmp = line.getOptionValue("input-file", "-");
    if ("-".equals(tmp)) {
        in = System.in;
    } else {
        try {
            in = new FileInputStream(tmp);
        } catch (FileNotFoundException e) {
            System.err.println("input file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    PrintStream out = System.out;
    tmp = line.getOptionValue("output-file", "-");
    if ("-".equals(tmp)) {
        out = System.out;
    } else {
        try {
            out = new PrintStream(new FileOutputStream(tmp));
        } catch (FileNotFoundException e) {
            System.err.println("output file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET);
    chart.setStyleSheet(tmp);

    try {
        chart.parseInput(in);
    } catch (IOException e) {
        System.err.println("I/O error while reading input");
        System.exit(1);
    } catch (net.cliftonsnyder.svgchart.parse.ParseException e) {
        System.err.println("error parsing input: " + e.getMessage());
    }

    chart.createChart();

    try {
        chart.printChart(out, true);
    } catch (IOException e) {
        System.err.println("error serializing output");
        System.exit(1);
    }
}

From source file:MatcherEndParamExample.java

public static void main(String args[]) {
    Pattern p = Pattern.compile("B(on)d");

    String candidateString = "My name is Bond. James Bond.";

    String matchHelper[] = { "               ^", "              ^", "                           ^",
            "                          ^" };
    Matcher matcher = p.matcher(candidateString);

    matcher.find();/*from w w w. j av  a2  s  .  c  o m*/
    int endIndex = matcher.end(0);
    System.out.println(candidateString);
    System.out.println(matchHelper[0] + endIndex);

    int nextIndex = matcher.end(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[1] + nextIndex);

    matcher.find();
    endIndex = matcher.end(0);
    System.out.println(candidateString);
    System.out.println(matchHelper[2] + endIndex);

    nextIndex = matcher.end(1);
    System.out.println(candidateString);
    System.out.println(matchHelper[3] + nextIndex);
}

From source file:com.movielabs.availstool.AvailsTool.java

public static void main(String[] args) throws Exception {
    String fileName, outFile, sheetName;
    int sheetNum = -1;

    Logger log = LogManager.getLogger(AvailsTool.class.getName());
    log.info("Initializing logger");

    Options options = new Options();
    options.addOption(Opts.v.name(), false, "verbose mode");
    options.addOption(Opts.s.name(), true, "specify sheet");
    options.addOption(Opts.f.name(), true, "specify file name");
    options.addOption(Opts.o.name(), true, "specify output file name");
    options.addOption(Opts.sstoxml.name(), false, "convert avails spreadsheet to XML");
    options.addOption(Opts.xmltoss.name(), false, "convert avails XML to a spreadsheet");
    options.addOption(Opts.dumpsheet.name(), false, "dump a single sheet from a spreadsheet");
    options.addOption(Opts.dumpss.name(), false, "dump a spreadsheet file");
    options.addOption(Opts.wx.name(), false, "treat warning as fatal error");
    options.addOption(Opts.clean.name(), false, "clean up data entries");

    CommandLineParser cli = new DefaultParser();

    try {//ww w . ja  va2  s  .c om
        CommandLine cmd = cli.parse(options, args);
        boolean optToXML = cmd.hasOption(Opts.sstoxml.name());
        boolean optToSS = cmd.hasOption(Opts.xmltoss.name());
        boolean optDumpSS = cmd.hasOption(Opts.dumpss.name());
        boolean optDumpSheet = cmd.hasOption(Opts.dumpsheet.name());
        fileName = cmd.getOptionValue(Opts.f.name());
        sheetName = cmd.getOptionValue(Opts.s.name());
        boolean clean = cmd.hasOption(Opts.clean.name());
        boolean wx = cmd.hasOption(Opts.wx.name());
        boolean verbose = cmd.hasOption(Opts.v.name());
        AvailSS ss;
        AvailsSheet as;
        String message;

        if (sheetName != null) {
            Pattern pat = Pattern.compile("^\\d+$");
            Matcher m = pat.matcher(sheetName);
            if (m.matches())
                sheetNum = Integer.parseInt(sheetName);
        }

        if (fileName == null)
            throw new ParseException("input file not specified");

        if (!(optToXML | optToSS | optDumpSS | optDumpSheet))
            throw new ParseException("missing operation");

        if (optToXML) {
            if (optToSS | optDumpSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            outFile = cmd.getOptionValue(Opts.o.name());
            if (outFile == null)
                throw new ParseException("output file not specified");

            ss = new AvailSS(fileName, log, wx, clean);
            if (sheetNum < 0)
                as = ss.addSheet(sheetName);
            else
                as = ss.addSheet(sheetNum);
            message = "toXML file: " + fileName + " sheet: " + sheetName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            log.info("Options: -clean:" + clean + "; -wx:" + wx + "; output file: " + outFile);
            String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
            String shortDesc = String.format("generated XML from %s:%s on %s", fileName, sheetName, timeStamp);
            as.makeXMLFile(outFile, shortDesc);
        } else if (optToSS) {
            if (optToXML | optDumpSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            // TODO implement this
            outFile = cmd.getOptionValue(Opts.o.name());
            if (outFile == null)
                throw new ParseException("output file not specified");
            AvailXML x = new AvailXML(fileName, log);
            x.makeSS(outFile);
        } else if (optDumpSS) {
            if (optToXML | optToSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            message = "dumping file: " + fileName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            AvailSS.dumpFile(fileName);
        } else { // dumpSheet
            if (sheetName == null)
                throw new ParseException("sheet name not specified");
            message = "dumping file: " + fileName + " sheet: " + sheetName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            ss = new AvailSS(fileName, log, wx, clean);
            if (sheetNum < 0)
                as = ss.addSheet(sheetName);
            else
                as = ss.addSheet(sheetNum);

            ss.dumpSheet(sheetName);
        }
    } catch (ParseException exp) {
        System.out.println("bad command line: " + exp.getMessage());
        usage();
        System.exit(-1);
    }
}

From source file:WordCount.java

public static void main(String args[]) throws Exception {
    String filename = "WordCount.java";

    // Map File from filename to byte buffer
    FileInputStream input = new FileInputStream(filename);
    FileChannel channel = input.getChannel();
    int fileLength = (int) channel.size();
    MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength);

    // Convert to character buffer
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);

    // Create line pattern
    Pattern linePattern = Pattern.compile(".*$", Pattern.MULTILINE);

    // Create word pattern
    Pattern wordBreakPattern = Pattern.compile("[\\p{Punct}\\s}]");

    // Match line pattern to buffer
    Matcher lineMatcher = linePattern.matcher(charBuffer);

    Map map = new TreeMap();
    Integer ONE = new Integer(1);

    // For each line
    while (lineMatcher.find()) {
        // Get line
        CharSequence line = lineMatcher.group();

        // Get array of words on line
        String words[] = wordBreakPattern.split(line);

        // For each word
        for (int i = 0, n = words.length; i < n; i++) {
            if (words[i].length() > 0) {
                Integer frequency = (Integer) map.get(words[i]);
                if (frequency == null) {
                    frequency = ONE;/*  ww w .  ja  v  a 2s  .c o m*/
                } else {
                    int value = frequency.intValue();
                    frequency = new Integer(value + 1);
                }
                map.put(words[i], frequency);
            }
        }
    }
    System.out.println(map);
}

From source file:MainClass.java

public static void main(String args[]) {
    // create regular expression
    Pattern expression = Pattern.compile("J.*\\d[0-35-9]-\\d\\d-\\d\\d");

    String string1 = "Jack's Birthday is 05-12-75\n" + "Joe's Birthday is 11-04-68\n"
            + "Tom's Birthday is 04-28-73\n" + "Lee" + "s Birthday is 12-17-77";

    // match regular expression to string and print matches
    Matcher matcher = expression.matcher(string1);

    while (matcher.find())
        System.out.println(matcher.group());
}

From source file:com.hp.avmon.trap.service.TrapService.java

public static void main(String[] args) {
    String text = "{3}123{3}{10}";

    Pattern p = Pattern.compile(".*?(\\{.+?\\})");

    Matcher m = p.matcher(text);
    while (m.find()) {
        System.out.println(m.group(1));
    }/*from w  ww .j av a 2 s  .  com*/
}

From source file:MainClass.java

public static void main(String args[]) {

    String phrase = "a word word";
    String duplicatePattern = "\\b(\\w+) \\1\\b";

    Pattern p = null;
    try {//ww  w .j  a  v a2s  .co  m
        p = Pattern.compile(duplicatePattern);
    } catch (PatternSyntaxException pex) {
        pex.printStackTrace();
        System.exit(0);
    }
    // count the number of matches.
    int matches = 0;

    // get the matcher
    Matcher m = p.matcher(phrase);
    String val = null;

    // find all matching Strings
    while (m.find()) {
        val = ":" + m.group() + ":";
        System.out.println(val);
        matches++;
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Pattern pattern = Pattern.compile("pattern");
    FileInputStream input = new FileInputStream("file.txt");
    FileChannel channel = input.getChannel();

    ByteBuffer bbuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size());
    CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);

    Matcher matcher = pattern.matcher(cbuf);
    while (matcher.find()) {
        String match = matcher.group();
        System.out.println(match);
    }/* www .j a v  a  2s  . c  o m*/
}

From source file:core.plugin.mybatis.PageInterceptor.java

public static void main(String[] args) {
    List<String> tests = new ArrayList<String>();
    tests.add("select count(*) from abc \n\t\t where\n abc");
    tests.add("SELECT COUNT(*) from abc");
    tests.add(" select count (*) from abc");
    tests.add(" select count( *) from abc");
    tests.add("select count( * ),id from abc");
    tests.add("select * from abc");
    tests.add("select abc,test,fdas from abc");
    tests.add("select count(adb) from abc");
    tests.add("select count(0) from abc");
    tests.add("select min(count(*)) from abc");
    tests.add("update min(count(*)) from abc");
    tests.add("delete min(count(*)) from abc");
    Pattern p1 = Pattern.compile(SQL_SELECT_REGEX, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    Pattern p2 = Pattern.compile(SQL_COUNT_REGEX, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    for (String str : tests) {
        Matcher m1 = p1.matcher(str);
        Matcher m2 = p2.matcher(str);
        System.out.println("?: " + str);
        System.out.println(" select?? " + m1.matches());
        System.out.println(" count?? " + m2.matches());
        System.out.println();/*from   w w  w . ja  v  a 2  s  .co  m*/
    }
}

From source file:com.github.aliteralmind.codelet.examples.non_xbn.PrintJDBlocksStartStopLineNumsXmpl.java

/**
   <p>The main function.</p>
 *//*from   w w w  .j a v a  2  s .  c  om*/
public static final void main(String[] as_1RqdJavaSourcePath) {

    //Read command-line parameter
    String sJPath = null;
    try {
        sJPath = as_1RqdJavaSourcePath[0];
    } catch (ArrayIndexOutOfBoundsException aibx) {
        throw new NullPointerException(
                "Missing one-and-only required parameter: Path to java source-code file.");
    }
    System.out.println("Java source: " + sJPath);

    //Establish line-iterator
    Iterator<String> lineItr = null;
    try {
        lineItr = FileUtils.lineIterator(new File(sJPath)); //Throws npx if null
    } catch (IOException iox) {
        throw new RTIOException("PrintJDBlocksStartStopLinesXmpl", iox);
    }
    Pattern pTrmdJDBlockStart = Pattern.compile("^[\\t ]*/\\*\\*");

    String sDD = "..";
    int lineNum = 1;
    boolean bInJDBlock = false;
    while (lineItr.hasNext()) {
        String sLn = lineItr.next();
        if (!bInJDBlock) {
            if (pTrmdJDBlockStart.matcher(sLn).matches()) {
                bInJDBlock = true;
                System.out.print(lineNum + sDD);
            }
        } else if (sLn.indexOf("*/") != -1) {
            bInJDBlock = false;
            System.out.println(lineNum);
        }
        lineNum++;
    }
    if (bInJDBlock) {
        throw new IllegalStateException("Reach end of file. JavaDoc not closed.");
    }
}