List of usage examples for java.util.regex Matcher group
public String group()
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); }/*from w w w.j a v a 2 s . c om*/ 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); }//from w w w. ja va 2s.c o m if (val == null) { System.out.println("NO MATCHES: "); } }
From source file:com.adobe.aem.demomachine.RegExp.java
public static void main(String[] args) throws IOException { String fileName = null;/*from ww w . j a va2s . c om*/ 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 {/*from ww w .j av a2 s .co m*/ 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()); } } }
From source file:com.github.liyp.test.TestMain.java
@SuppressWarnings("unchecked") public static void main(String[] args) { // add a shutdown hook to stop the server Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override// w w w . j av a2s . c om public void run() { System.out.println("########### shoutdown begin...."); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("########### shoutdown end...."); } })); System.out.println(args.length); Iterator<String> iterator1 = IteratorUtils .arrayIterator(new String[] { "one", "two", "three", "11", "22", "AB" }); Iterator<String> iterator2 = IteratorUtils.arrayIterator(new String[] { "a", "b", "c", "33", "ab", "aB" }); Iterator<String> chainedIter = IteratorUtils.chainedIterator(iterator1, iterator2); System.out.println("=================="); Iterator<String> iter = IteratorUtils.filteredIterator(chainedIter, new Predicate() { @Override public boolean evaluate(Object arg0) { System.out.println("xx:" + arg0.toString()); String str = (String) arg0; return str.matches("([a-z]|[A-Z]){2}"); } }); while (iter.hasNext()) { System.out.println(iter.next()); } System.out.println("==================="); System.out.println("asas".matches("[a-z]{4}")); System.out.println("Y".equals(null)); System.out.println(String.format("%02d", 1000L)); System.out.println(ArrayUtils.toString(splitAndTrim(" 11, 21,12 ,", ","))); System.out.println(new ArrayList<String>().toString()); JSONObject json = new JSONObject("{\"keynull\":null}"); json.put("bool", false); json.put("keya", "as"); json.put("key2", 2212222222222222222L); System.out.println(json); System.out.println(json.get("keynull").equals(null)); String a = String.format("{\"id\":%d,\"method\":\"testCrossSync\"," + "\"circle\":%d},\"isEnd\":true", 1, 1); System.out.println(a.getBytes().length); System.out.println(new String[] { "a", "b" }); System.out.println(new JSONArray("[\"aa\",\"\"]")); String data = String.format("%9d %s", 1, RandomStringUtils.randomAlphanumeric(10)); System.out.println(data.getBytes().length); System.out.println(ArrayUtils.toString("1|2| 3| 333||| 3".split("\\|"))); JSONObject j1 = new JSONObject("{\"a\":\"11111\"}"); JSONObject j2 = new JSONObject(j1.toString()); j2.put("b", "22222"); System.out.println(j1 + " | " + j2); System.out.println("======================"); String regex = "\\d+(\\-\\d+){2} \\d+(:\\d+){2}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher("2015-12-28 15:46:14 _NC250_MD:motion de\n"); String eventDate = matcher.find() ? matcher.group() : ""; System.out.println(eventDate); }
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;//from ww w.ja va 2 s .co m } else { int value = frequency.intValue(); frequency = new Integer(value + 1); } map.put(words[i], frequency); } } } System.out.println(map); }
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 .co m 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: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 ww .j a v a 2 s. c om 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:com.baifendian.swordfish.execserver.job.AbstractYarnJob.java
public static void main(String[] args) { String msg = "INFO : Starting Job = job_1499151077551_0548, Tracking URL = http://bgsbtsp0006-dqf:8088/proxy/application_1499151077551_0548/\n"; // application id Matcher matcher = APPLICATION_REGEX.matcher(msg); while (matcher.find()) { System.out.println(matcher.group()); }/* w w w .ja v a2 s . co m*/ // job id matcher = JOB_REGEX.matcher(msg); while (matcher.find()) { System.out.println(matcher.group()); } // ? msg msg = "sh.execserver.runner.node.NodeRunner:application[147] - hive execute log : INFO : Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 0"; // application id matcher = APPLICATION_REGEX.matcher(msg); while (matcher.find()) { System.out.println(matcher.group()); } // job id matcher = JOB_REGEX.matcher(msg); while (matcher.find()) { System.out.println(matcher.group()); } }
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();/*from ww w . jav a2 s . c o 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(); } }