public static void verifyCommand( String args[], @SuppressWarnings("unused") String help, Pattern[] patterns, int low, int high) { String message = ""; if (args.length > high) { message = "too many arguments"; } else if (args.length < low) { message = "too few arguments"; } else { for (int i = 0; patterns != null && i < patterns.length && i < args.length; i++) { if (patterns[i] != null) { Matcher m = patterns[i].matcher(args[i]); if (!m.matches()) message += String.format( "Argument %s (%s) does not match %s%n", i, args[i], patterns[i].pattern()); } } } if (message.length() != 0) { StringBuilder sb = new StringBuilder(); String del = "${"; for (String arg : args) { sb.append(del); sb.append(arg); del = ";"; } sb.append("}, is not understood. "); sb.append(message); throw new IllegalArgumentException(sb.toString()); } }
public static String removePrimerLR(String pname) { Matcher m = primerLRPattern.matcher(pname); if (!m.matches()) { throw new IllegalArgumentException(pname); } return m.group(1); }
public static String getChrom(String chromName) { Matcher m = chromPattern.matcher(chromName); if (!m.matches()) { return chromName; } return m.group(1); }
private static String expand(String str) { if (str == null) { return null; } StringBuilder result = new StringBuilder(); Pattern re = Pattern.compile("^(.*?)\\$\\{([^}]*)\\}(.*)"); while (true) { Matcher matcher = re.matcher(str); if (matcher.matches()) { result.append(matcher.group(1)); String property = matcher.group(2); if (property.equals("/")) { property = "file.separator"; } String value = System.getProperty(property); if (value != null) { result.append(value); } str = matcher.group(3); } else { result.append(str); break; } } return result.toString(); }
public static void main(String[] args) throws IOException { // Get input html StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String str = in.readLine(); str != null; str = in.readLine()) { sb.append("\n" + str); } String html = sb.toString(); // Match all the questions Matcher matcher = Pattern.compile( "<\\s*div\\s+class\\s*=\\s*\"question-summary\"\\s*id\\s*=\\s*\"question-summary-(?<id>\\d+)\"\\s*>" + ".*?<\\s*div\\s+class\\s*=\\s*\"summary\"\\s*>" + ".*?<\\s*a\\s+.*?class\\s*=\\s*\"question-hyperlink\"\\s*>" + "(?<title>.*?)" + "</\\s*a\\s*>.*?<\\s*div\\s+class\\s*=\\s*\"user-action-time\"\\s*>" + ".*?<\\s*span\\s+.*?>(?<time>.*?)</\\s*span\\s*>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL) .matcher(html); // Output the information while (matcher.find()) { String id = matcher.group("id"); String title = matcher.group("title"); String time = matcher.group("time"); System.out.println(id + ";" + title + ";" + time); } }
/** * Takes a line and looks for an archive request tag. If one is found, the information from the * tag is returned as an <CODE>ArchiveRequest</CODE>. If a tag is found, the data in the tag is * stored in the <CODE>HashMap</CODE> provided. * * @param currentLine The line in which to look for the archive tag. * @param group The <CODE>ArchiveGroup</CODE> to which to add the <CODE>ArchiveRequest</CODE>. Can * be <CODE>null</CODE>. * @param template The <CODE>Template</CODE> to which the <CODE>ArchiveRequest</CODE> belongs. * @return The archive request tag data as an instance of <CODE>ArchiveRequest</CODE>, <CODE>null * </CODE> if the line passed in does not contain an arFile tag. */ private ArchiveRequest parseArchiveRequestTag( String currentLine, ArchiveGroup group, Template template) { ArchiveRequest archiveTag; Matcher currentMatcher = archiveRequestPattern.matcher(currentLine); if (currentMatcher.find()) { String fileName = currentMatcher.group(1); archiveTag = template.getArchiveRequest(fileName); if (archiveTag == null) { archiveTag = new ArchiveRequest(fileName); template.addArchiveRequest(archiveTag); } if (group != null) { // Creating a new request object because the requests // in the groups flagged as not in database will mean the // group - request association is not in database. Requests // in the archiveRequests map flagged as not in database // means the request record is not there. String requestFileName = archiveTag.getFileName(); String requestFileLocation = archiveTag.getFileLocation(); ArchiveRequest groupRequest = new ArchiveRequest(requestFileLocation, requestFileName); group.addArchiveRequest(groupRequest); } } else archiveTag = null; return archiveTag; }
/** * Get the noun and verb <roots> (i.e. 'the highest' synsets in WordNet) from the particular * 'icfile' (Information Content) that you are applying. Store a noun <root>: a synset offset * number of type Integer in nounroots: an ArrayList<Integer> defined in the constructor of this * class. Store a verb <root>: a synset offset number of type Integer in verbroots: an * ArrayList<Integer> defined in the constructor of this class. * * <p>An example line in an 'icfile', showing a noun <root>: 1740n 128767 ROOT */ private void getRoots() { Pattern pn = Pattern.compile("[0-9]+n [0-9]+ ROOT"); // find noun <root> Pattern pv = Pattern.compile("[0-9]+v [0-9]+ ROOT"); // find verb <root> Matcher m = null; String root = ""; try { BufferedReader in = new BufferedReader(new FileReader(icfile)); String line; while ((line = in.readLine()) != null) { // nouns m = pn.matcher(line); if (m.matches()) { root = (line.split("\\s")[0]).split("n")[0]; // !!! double split !!! nounroots.add(Integer.parseInt(root)); } // verbs m = pv.matcher(line); if (m.matches()) { root = (line.split("\\s")[0]).split("v")[0]; // !!! double split !!! verbroots.add(Integer.parseInt(root)); } } in.close(); } catch (IOException e) { e.printStackTrace(); } }
public boolean isPresent2(String patternStr) { Pattern p = Pattern.compile(patternStr); Matcher m = p.matcher(string2); boolean b = m.matches(); return b; }
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (m != null) m.reset(root.relativize(dir).toString()); return m == null || m.matches() || m.hitEnd() ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE; }
public static void main(String[] args) { String inputStr = null; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { while ((inputStr = reader.readLine()) != null) { inputStr = inputStr.trim(); if (DEST_MATCHER.reset(inputStr).matches()) { System.out.println("Destination field!\n"); } else if (SOURCE_MATCHER.reset(inputStr).matches()) { System.out.println("Source field!\n"); } else if (STRING_MATCHER.reset(inputStr).matches()) { System.out.println("String literal!\n"); } else if (VAR_MATCHER.reset(inputStr).matches()) { System.out.println("Variable!\n"); } else if (NUM_MATCHER.reset(inputStr).matches()) { System.out.println("Number!\n"); } else { System.out.println("Huh???\n"); } } } catch (Exception ioe) { System.out.println("Exception: " + ioe.toString()); ioe.printStackTrace(); } }
private InstanceList readFile() throws IOException { String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(fileName), encoding); ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); pipeList.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}\\p{L}+"))); pipeList.add(new TokenSequence2FeatureSequence()); InstanceList testing = new InstanceList(new SerialPipes(pipeList)); try { while (scanner.hasNextLine()) { String text = scanner.nextLine(); text = text.replaceAll("\\x0d", ""); Pattern patten = Pattern.compile("^(.*?),(.*?),(.*)$"); Matcher matcher = patten.matcher(text); if (matcher.find()) { docIds.add(matcher.group(1)); testing.addThruPipe(new Instance(matcher.group(3), null, "test instance", null)); } } } finally { scanner.close(); } return testing; }
/** * Get dependencies of a source file. * * @param path The canonical path of source file. * @return Path of dependencies. */ private ArrayList<String> getDependencies(String path) { if (!dependenceMap.containsKey(path)) { ArrayList<String> dependencies = new ArrayList<String>(); Matcher m = PATTERN_REQUIRE.matcher(read(path, charset)); while (m.find()) { // Decide which root path to use. // Path wrapped in <> is related to root path. // Path wrapped in "" is related to parent folder of the source file. String root = null; if (m.group(1).equals("<")) { root = this.root; } else { root = new File(path).getParent(); } // Get path of required file. String required = m.group(2); File f = new File(root, required); if (f.exists()) { dependencies.add(canonize(f)); } else { App.exit("Cannot find required file " + required + " in " + path); } } dependenceMap.put(path, dependencies); } return dependenceMap.get(path); }
@Override public void actionPerformed(ActionEvent e) { if (td.getTabCount() > 0) { TextDocument ta = (TextDocument) td.getComponentAt(td.getSelectedIndex()); Pattern pn = Pattern.compile(tf1.getText()); Matcher mt = pn.matcher(ta.getText()); if (e.getSource() == jb2) { // 取代 ta.setText(mt.replaceAll(tf2.getText())); } else if (e.getSource() == jb1) { // 尋找 Highlighter hl = ta.getHighlighter(); hl.removeAllHighlights(); while (mt.find()) { try { hl.addHighlight( mt.start(), mt.end(), new DefaultHighlighter.DefaultHighlightPainter(null)); } catch (Exception ex) { } } // 開啟及關閉介面 } else if (e.getSource() == replace_searchMenuItem) { System.out.println("Replace/Search is show:" + !show); if (show) { getContentPane().remove(jp); show = false; } else { getContentPane().add(jp, BorderLayout.SOUTH); show = true; } validate(); // 刷新容器 } } else if (e.getSource() == replace_searchMenuItem) { JOptionPane.showMessageDialog( null, "尚無檔案,無法使用!", "Repace/Search error", JOptionPane.ERROR_MESSAGE); } }
public String getArtifactIdFromCoord(String coord) { Matcher m = COORD_P.matcher(coord); if (m.matches()) { return m.group(2); } else { return null; } }
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.isRegularFile()) { if (m != null) m.reset(root.relativize(file).toString()); if (m == null || m.matches()) futures.add(exec.submit(new FileLoader(root, file, blocSize))); } return FileVisitResult.CONTINUE; }
public BasicSpellChecker(String file) throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); Pattern p = Pattern.compile("\\w+"); for (String temp = ""; temp != null; temp = in.readLine()) { Matcher m = p.matcher(temp.toLowerCase()); while (m.find()) nWords.put((temp = m.group()), nWords.containsKey(temp) ? nWords.get(temp) + 1 : 1); } in.close(); }
// todo: give options for document splitting. A line or the whole file or // sentence splitting as now public Iterator<List<IN>> getIterator(Reader r) { Tokenizer<IN> tokenizer = tokenizerFactory.getTokenizer(r); // PTBTokenizer.newPTBTokenizer(r, false, true); List<IN> words = new ArrayList<IN>(); IN previous = tokenFactory.makeToken(); StringBuilder prepend = new StringBuilder(); /* * This changes SGML tags into whitespace -- it should maybe be moved * elsewhere */ while (tokenizer.hasNext()) { IN w = tokenizer.next(); String word = w.get(CoreAnnotations.TextAnnotation.class); Matcher m = sgml.matcher(word); if (m.matches()) { String before = StringUtils.getNotNullString(w.get(CoreAnnotations.BeforeAnnotation.class)); String after = StringUtils.getNotNullString(w.get(CoreAnnotations.AfterAnnotation.class)); prepend.append(before).append(word); String previousTokenAfter = StringUtils.getNotNullString(previous.get(CoreAnnotations.AfterAnnotation.class)); previous.set(AfterAnnotation.class, previousTokenAfter + word + after); // previous.appendAfter(w.word() + w.after()); } else { String before = StringUtils.getNotNullString(w.get(CoreAnnotations.BeforeAnnotation.class)); if (prepend.length() > 0) { w.set(BeforeAnnotation.class, prepend.toString() + before); // w.prependBefore(prepend.toString()); prepend = new StringBuilder(); } words.add(w); previous = w; } } List<List<IN>> sentences = wts.process(words); String after = ""; IN last = null; for (List<IN> sentence : sentences) { int pos = 0; for (IN w : sentence) { w.set(PositionAnnotation.class, Integer.toString(pos)); after = StringUtils.getNotNullString(w.get(CoreAnnotations.AfterAnnotation.class)); w.remove(AfterAnnotation.class); last = w; } } if (last != null) { last.set(AfterAnnotation.class, after); } return sentences.iterator(); }
// remove non-word characters and everything after ":::" from the // program point name, leaving PackageName.ClassName.MethodName private static String cleanup_pptname(String pptname) { int index; if ((index = pptname.indexOf("(")) > 0) { pptname = pptname.substring(0, index); } if (pptname.endsWith(".")) pptname = pptname.substring(0, pptname.length() - 2); Matcher m = non_word_pattern.matcher(pptname); return m.replaceAll("."); }
void search() { int i=0; Matcher matcher=new Matcher(a,b); while (i<a.length-1) { int j=i; matcher.findBiggestMatchForFrom(i,j); findbiggestmatchfrom(i,j,0); } }
public int getStatus() { if (status != null) { return status; } matcher = STATUS_PATTERN.matcher(firstLine); if (matcher.find()) { status = Integer.parseInt(matcher.group(1)); } return status; }
public static int[] decodePrimerName(String pname) { Matcher m = primerNamePattern.matcher(pname); if (!m.matches()) { throw new IllegalArgumentException(pname); } int[] a = new int[3]; a[0] = Integer.parseInt(m.group(1)); a[1] = Integer.parseInt(m.group(2)); a[2] = Integer.parseInt(m.group(3)); return a; }
public String getResult() { if (result != null) { return result; } matcher = RESULT_PATTERN.matcher(firstLine); if (matcher.find()) { result = matcher.group(1); } return result; }
/** * Converts a colour from #rrggbb to Java Color object. * * @param rgb String e.g. #ff00ee * @return Colour * @throws IllegalArgumentException If colour string is not valid */ protected Color convertRgb(String rgb) throws IllegalArgumentException { // Get colour parameter Matcher m = REGEX_RGB.matcher(rgb); if (!m.matches()) { throw new IllegalArgumentException( "MathML invalid colour '" + rgb + "'; expected #rrggbb (lower-case)"); } return new Color( Integer.parseInt(m.group(1), 16), Integer.parseInt(m.group(2), 16), Integer.parseInt(m.group(3), 16)); }
void findRemoveDirectives(boolean clean) { // if ( clean ) editor.startCompoundEdit(); Sketch sketch = editor.getSketch(); for (int i = 0; i < sketch.getCodeCount(); i++) { SketchCode code = sketch.getCode(i); String program = code.getProgram(); StringBuffer buffer = new StringBuffer(); Matcher m = pjsPattern.matcher(program); while (m.find()) { String mm = m.group(); // TODO this urgently needs tests .. /* remove framing */ mm = mm.replaceAll("^\\/\\*\\s*@pjs", "").replaceAll("\\s*\\*\\/\\s*$", ""); /* fix multiline nice formatting */ mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*,[\\s]*[\\n\\r]+", "$1,"); /* fix multiline version without semicolons */ mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*[\\n\\r]+", "$1;"); mm = mm.replaceAll("\n", " ").replaceAll("\r", " "); // System.out.println(mm); if (clean) { m.appendReplacement(buffer, ""); } else { String[] directives = mm.split(";"); for (String d : directives) { // System.out.println(d); parseDirective(d); } } } if (clean) { m.appendTail(buffer); // TODO: not working! code.setProgram(buffer.toString()); code.setModified(true); } } if (clean) { // editor.stopCompoundEdit(); editor.setText(sketch.getCurrentCode().getProgram()); sketch.setModified(false); sketch.setModified(true); } }
protected static String getMethodName(Test test) { String className; String desc = test.toString(); Matcher matcher = methodpattern.matcher(desc); if (matcher.matches()) { className = matcher.group(1); } else { className = desc; } return className; }
/** * Returns an integer corresponding to the given experiment name. If the argument matches an * experiment name exactly, then that index is returned. Otherwise, the argument is treated as a * regexp, and the index of some experiment that matches it is returned. * * @param key The name, or regexp for the name, of the experiment to find. * @return The array index of the experiment, or -1 if not found. */ public int findExperiment(String key) { if (exptIndices.containsKey(key)) { return exptIndices.get(key); } Pattern p = Pattern.compile(key); for (String k : exptIndices.keySet()) { Matcher m = p.matcher(k); if (m.matches()) { return exptIndices.get(k); } } return -1; }
/** * Takes a line and looks for an archive group tag. If one is found, the information from the tag * is returned as an <CODE>ArchiveGroup</CODE>. If a tag is found, the data in the tag is stored * in the <CODE>HashMap</CODE> provided. * * @param currentLine The line in which to look for the archive tag. * @param template The <CODE>Template</CODE> to which the <CODE>ArchiveGroup</CODE> belongs. * @return The archive request tag data as an instance of <CODE>ArchiveGroup</CODE>, <CODE>null * </CODE> if the line passed in does not contain an arFile tag. */ private ArchiveGroup parseArchiveGroupTag(String currentLine, Template template) { ArchiveGroup archiveTag; Matcher currentMatcher = archiveRequestPattern.matcher(currentLine); if (currentMatcher.find()) { String fileName = currentMatcher.group(1); archiveTag = template.getArchiveGroup(fileName); if (archiveTag == null) { File groupFile = new File(fileName); archiveTag = new ArchiveGroup(groupFile.getParent(), groupFile.getName()); template.addArchiveGroup(archiveTag); } } else archiveTag = null; return archiveTag; }
public void testBaseUrl() throws Exception { sau1 = setupSimAu(simAuConfig(tempDirPath)); createContent(sau1); crawlContent(sau1); CachedUrlSet cus1 = sau1.getAuCachedUrlSet(); tempDirPath2 = getTempDir().getAbsolutePath() + File.separator; Configuration config2 = simAuConfig(tempDirPath2); config2.put("base_url", "http://anotherhost.org/"); SimulatedArchivalUnit sau2 = setupSimAu(config2); createContent(sau2); crawlContent(sau2); CachedUrlSet cus2 = sau1.getAuCachedUrlSet(); List urls1 = auUrls(sau1); List urls2 = auUrls(sau2); Pattern pat = Pattern.compile("http://([^/]+)(/.*)$"); List<String> l1 = auUrls(sau1); List<String> l2 = auUrls(sau2); assertEquals(l1.size(), l2.size()); for (int ix = 0; ix < l1.size(); ix++) { Matcher m1 = pat.matcher(l1.get(ix)); assertTrue(m1.matches()); Matcher m2 = pat.matcher(l2.get(ix)); assertTrue(m2.matches()); assertEquals("www.example.com", m1.group(1)); assertEquals("anotherhost.org", m2.group(1)); assertEquals(m1.group(2), m2.group(2)); } }
public void run() { // each file is processed into a local hash table and then merged with the global results // this will cause much less contention on the global table, but still avoids a sequential // update Hashtable<String, Integer> local_results = new Hashtable<String, Integer>(WordCountJ.HASH_SIZE, WordCountJ.LF); // grab a file to work on String cf; while ((cf = files.poll()) != null) { try { BufferedReader input = new BufferedReader(new FileReader(cf)); String text; // well go line-by-line... maybe this is not the fastest while ((text = input.readLine()) != null) { // parse words Matcher matcher = pattern.matcher(text); while (matcher.find()) { String word = matcher.group(1); if (local_results.containsKey(word)) { local_results.put(word, 1 + local_results.get(word)); } else { local_results.put(word, 1); } } } input.close(); } catch (Exception e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); return; } // merge local hashmap with shared one,could have a // seperate thread do this but that might be cheating Iterator<Map.Entry<String, Integer>> updates = local_results.entrySet().iterator(); while (updates.hasNext()) { Map.Entry<String, Integer> kv = updates.next(); String k = kv.getKey(); Integer v = kv.getValue(); synchronized (results) { if (results.containsKey(k)) { results.put(k, v + results.get(k)); } else { results.put(k, v); } } } local_results.clear(); } }
private String htmlize(String msg) { StringBuilder sb = new StringBuilder(); Pattern patMsgCat = Pattern.compile("\\[(.+?)\\].*"); msg = msg.replace("&", "&").replace("<", "<").replace(">", ">"); for (String line : msg.split(lineSep)) { Matcher m = patMsgCat.matcher(line); String cls = "normal"; if (m.matches()) { cls = m.group(1); } line = "<span class='" + cls + "'>" + line + "</span>"; sb.append(line).append("<br>"); } return sb.toString(); }