public String _range(String args[]) { verifyCommand(args, _rangeHelp, _rangePattern, 2, 3); Version version = null; if (args.length >= 3) version = new Version(args[2]); else { String v = domain.getProperty("@"); if (v == null) return null; version = new Version(v); } String spec = args[1]; Matcher m = RANGE_MASK.matcher(spec); m.matches(); String floor = m.group(1); String floorMask = m.group(2); String ceilingMask = m.group(3); String ceiling = m.group(4); String left = version(version, floorMask); String right = version(version, ceilingMask); StringBuilder sb = new StringBuilder(); sb.append(floor); sb.append(left); sb.append(","); sb.append(right); sb.append(ceiling); String s = sb.toString(); VersionRange vr = new VersionRange(s); if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) { domain.error( "${range} macro created an invalid range %s from %s and mask %s", s, version, spec); } return sb.toString(); }
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 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)); } }
/** * This method exports the single pattern decision instance to the XML. It MUST be called by an * XML exporter, as this will not have a complete header. * * @param ratDoc The ratDoc generated by the XML exporter * @return the SAX representation of the object. */ public Element toXML(Document ratDoc) { Element decisionE; RationaleDB db = RationaleDB.getHandle(); // Now, add pattern to doc String entryID = db.getRef(this); if (entryID == null) { entryID = db.addPatternDecisionRef(this); } decisionE = ratDoc.createElement("DR:patternDecision"); decisionE.setAttribute("rid", entryID); decisionE.setAttribute("name", name); decisionE.setAttribute("type", type.toString()); decisionE.setAttribute("phase", devPhase.toString()); decisionE.setAttribute("status", status.toString()); // decisionE.setAttribute("artifact", artifact); Element descE = ratDoc.createElement("description"); Text descText = ratDoc.createTextNode(description); descE.appendChild(descText); decisionE.appendChild(descE); // Add child pattern references... Iterator<Pattern> cpi = candidatePatterns.iterator(); while (cpi.hasNext()) { Pattern cur = cpi.next(); Element curE = ratDoc.createElement("refChildPattern"); Text curText = ratDoc.createTextNode("p" + new Integer(cur.getID()).toString()); curE.appendChild(curText); decisionE.appendChild(curE); } return decisionE; }
/** * Chooses files that match the specified pattern. * * @param file file filter * @param content content filter * @param root root directory * @return sorted file paths * @throws InterruptedException interruption */ String[] filter(final String file, final String content, final IOFile root) throws InterruptedException { final long id = ++filterId; final TreeSet<String> results = new TreeSet<>(); final int[] search = new TokenParser(Token.lc(Token.token(content))).toArray(); // glob pattern final ProjectCache pc = cache(root); if (file.contains("*") || file.contains("?")) { final Pattern pt = Pattern.compile(IOFile.regex(file)); for (final String path : pc) { final int offset = offset(path, true); if (pt.matcher(path.substring(offset)).matches() && filterContent(path, search)) { results.add(path); if (results.size() >= MAXHITS) break; } if (id != filterId) throw new InterruptedException(); } } else { // starts-with, contains, camel case final String pttrn = file.toLowerCase(Locale.ENGLISH).replace('\\', '/'); final HashSet<String> exclude = new HashSet<>(); final boolean pathSearch = pttrn.indexOf('/') != -1; for (int i = 0; i < (pathSearch ? 2 : 3); i++) { filter(pttrn, search, i, results, exclude, pathSearch, pc, id); } } return results.toArray(new String[results.size()]); }
public boolean isPresent2(String patternStr) { Pattern p = Pattern.compile(patternStr); Matcher m = p.matcher(string2); boolean b = m.matches(); return b; }
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; }
@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); } }
private void readPattern(BufferedInputStream in, Pattern p) throws IOException { // Pattern header length read(in, 4); // Packing type (always 0) in.read(); // Number of rows in pattern (1...256) int rows = make16Bit(read(in, 2)); // Packed patterndata size int size = make16Bit(read(in, 2)); int data[]; if (size == 0) { data = new int[0]; } else { byte[] b = read(in, size); data = new int[size]; for (int i = 0; i < size; i++) { data[i] = b[i]; } } p.setData(data); p.setRows(rows); }
protected Map<String, String> getAttributes() { if (attributes != null) { return attributes; } attributes = new HashMap<String, String>(); matcher = ADDITIONAL_ATTRIBUTES_PATTERN.matcher(firstLine); if (matcher.find()) { String s; Matcher attributeMatcher; s = matcher.group(2); attributeMatcher = ADDITIONAL_ATTRIBUTE_PATTERN.matcher(s); while (attributeMatcher.find()) { String key; String value; key = attributeMatcher.group(1); value = attributeMatcher.group(2); attributes.put(key.toLowerCase(Locale.ENGLISH), value); } } return attributes; }
private static final class MessageFormatter { private static final Pattern variablePattern = Pattern.compile("(?i)\\$(\\{[a-z0-9_]{1,}\\}|[a-z0-9_]{1,})"); private static final Pattern colorPattern = Pattern.compile("(?i)&[0-9A-FK-OR]"); private final Map<String, String> variables; public MessageFormatter() { variables = new HashMap<String, String>(); } public synchronized void setVariable(String variable, String value) { if (value == null) variables.remove(value); else variables.put(variable, value); } public synchronized String format(String message) { Matcher matcher = variablePattern.matcher(message); while (matcher.find()) { String variable = matcher.group(); variable = variable.substring(1); if (variable.startsWith("{") && variable.endsWith("}")) variable = variable.substring(1, variable.length() - 1); String value = variables.get(variable); if (value == null) value = ""; message = message.replaceFirst(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); } matcher = colorPattern.matcher(message); while (matcher.find()) message = message.substring(0, matcher.start()) + "\247" + message.substring(matcher.end() - 1); return message; } }
public class BlockFactory { private static final String BLOCK_IF = "if"; private static final String BLOCK_ELSEIF = "elseif"; private static final String BLOCK_ELSE = "else"; private static final String BLOCK_ENDIF = "endif"; private static final String BLOCK_FOR = "for"; private static final String BLOCK_ENDFOR = "endfor"; private static final String BLOCK_NAMEDBLOCK = "block"; private static final String BLOCK_ENDNAMEDBLOCK = "endblock"; private static final String BLOCK_EXTENDS = "extends"; private static final Pattern FOR_PATTERN = Pattern.compile("\\s*for\\s+(\\w+)\\s+in\\s+(\\w+)\\s*"); private static final Pattern FOR_KV_PATTERN = Pattern.compile("\\s*for\\s+(\\w+)\\s*,\\s*(\\w+)\\s+in\\s+(\\w+)\\s*"); private static final Pattern IF_PATTERN = Pattern.compile("\\s*(if)\\s*(.*)\\s*"); private static final Pattern BLOCK_PATTERN = Pattern.compile("\\s*(block)\\s*(.*)\\s*"); // Pattern.compile("\\s*for\\s+(\\w+)in\\s+(.+)\\s*"); public static BlockNode create(String blockText) { // {{{ String elements[] = blockText.trim().split("\\s+"); String blockType = elements[0].toLowerCase(); if (blockType.equals(BLOCK_IF)) { return new IfBlock(blockText.trim().substring(2).trim()); } else if (blockType.equals(BLOCK_ELSE)) { return new ElseBlock(); } else if (blockType.equals(BLOCK_ELSEIF)) { return new ElseBlock(blockText.trim().substring(6).trim()); } else if (blockType.equals(BLOCK_ENDIF)) { return new EndIfBlock(); } else if (blockType.equals(BLOCK_FOR)) { Matcher m = FOR_PATTERN.matcher(blockText); if (m.matches()) { return new ForBlock(m.group(1), m.group(2)); } else { Matcher m2 = FOR_KV_PATTERN.matcher(blockText); if (m2.matches()) { return new ForKeyValBlock(m2.group(1), m2.group(2), m2.group(3)); } else { System.out.println("badly formed for block"); return null; } } } else if (blockType.equals(BLOCK_ENDFOR)) { return new EndForBlock(); } else if (blockType.equals(BLOCK_NAMEDBLOCK)) { if (elements.length != 2) return null; // badly formed block return new StartNamedBlock(elements[1]); } else if (blockType.equals(BLOCK_ENDNAMEDBLOCK)) { return new EndNamedBlock(); } else if (blockType.equals(BLOCK_EXTENDS)) { if (elements.length != 2) return null; // badly formed block return new ExtendsNode(elements[1]); } return null; // TODO } // }}} }
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(); }
public static float calcFitness(int[] particle, LinkedList<PatternList> l) throws IOException { PatternList pl1 = l.getFirst(); PatternList pl2 = l.getLast(); float fit; int[] pagesArray = pl1.getPageArray(); float f1 = 0; float f2 = 0; for (int i = 0; i < particle.length - 2 + 1; i++) { int[] duo = new int[2]; for (int j = 0; j < 2; j++) { // System.out.println("\t\t"+this.dimensions[i + j]); duo[j] = pagesArray[particle[i + j]]; } Pattern current = pl2.seek(duo); if (current != null) { f2 += (current.getFreq() * (1000 * current.getConfidence())); } else if (current == null) { // System.out.print("\t\t duo : "); // new Pattern(duo).print(); fit = (float) -6.0; return fit; } } f2 = (f2 / ((particle.length - 2 + 1) * pl2.getTotalFreq() * pl2.getDistribution())); for (int i = 0; i < particle.length; i++) { Pattern current = pl1.seek(particle[i]); if (current == null) { fit = (float) 0.0; return (float) -6.0; } else { f1 += current.getFreq(); } } f1 = (f1 / (particle.length * pl1.getTotalFreq() * pl1.getDistribution())); // System.out.println("\t\t\tf2 freq : "+ f2); return fit = 1000 * ((1 * f1 + 3 * f2) / 4); // fitness da partícula 8,8,8 é :0.468331 // fitness da partícula 1,1,1 é :0.35263315 // fitness da partícula 6,6,7 é :0.050931655 // fitness da partícula 14,13,16 é :3.627465E-4 // fitness da partícula 8,8,8 é :0.039101 // fitness da partícula 1,1,1 é :0.029390793 // fitness da partícula 6,6,7 é :0.0042792875 // fitness da partícula 14,13,16 é :1.3224661E-4 }
String filter(String[] args, boolean include) { verifyCommand(args, String.format(_filterHelp, args[0]), null, 3, 3); Collection<String> list = new ArrayList<String>(Processor.split(args[1])); Pattern pattern = Pattern.compile(args[2]); for (Iterator<String> i = list.iterator(); i.hasNext(); ) { if (pattern.matcher(i.next()).matches() == include) i.remove(); } return Processor.join(list); }
// Derived from http://stackoverflow.com/a/3054692/250076 public static File getRelativeFile(File targetFile, File baseFile) { try { targetFile = targetFile.getCanonicalFile(); baseFile = baseFile.getCanonicalFile(); } catch (IOException ignored) { } String pathSeparator = File.separator; String basePath = baseFile.getAbsolutePath(); String normalizedTargetPath = normalize(targetFile.getAbsolutePath(), pathSeparator); String normalizedBasePath = normalize(basePath, pathSeparator); String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); StringBuilder common = new StringBuilder(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex]).append(pathSeparator); commonIndex++; } if (commonIndex == 0) { throw new Error( "No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + '\''); } boolean baseIsFile = true; if (baseFile.exists()) { baseIsFile = baseFile.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuilder relative = new StringBuilder(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append("..").append(pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return new File(relative.toString()); }
public String[] list(String regex) { Pattern pattern = Pattern.compile(regex); ArrayList<String> slist = new ArrayList<String>(); int count = 0; for (String s : dirList) { if (pattern.matcher(s).matches()) { count++; slist.add(s); } } return slist.toArray(new String[count]); }
/** * 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; }
/** * Returns a string built using a particular grammar. Single-quotes strings are counted as literal * strings, whereas all other strings appearing in the grammar require substitution with the * corresponding value from the extraparams hashmap. */ private String buildGrammar(String grammar, Map<String, String> extraparams) { StringBuilder outboundstring = new StringBuilder(); String[] fields = Pattern.compile("\\s+").split(grammar); for (int i = 0; i < fields.length; i++) { if (fields[i].substring(0, 1).equals("'")) { outboundstring.append(fields[i].substring(1, fields[i].length() - 1)); } else { outboundstring.append(extraparams.get(fields[i])); } } return outboundstring.toString(); }
public class RegexTest { public static final String DEST_REGEX = "^D\\w+\\w*$"; public static final Pattern DEST_PATTERN = Pattern.compile(DEST_REGEX); public static Matcher DEST_MATCHER = DEST_PATTERN.matcher(""); public static final String SOURCE_REGEX = "^S\\w+\\w*$"; public static final Pattern SOURCE_PATTERN = Pattern.compile(SOURCE_REGEX); public static Matcher SOURCE_MATCHER = SOURCE_PATTERN.matcher(""); public static final String STRING_REGEX = "^'[a-zA-Z_0-9 ]*'$"; public static final Pattern STRING_PATTERN = Pattern.compile(STRING_REGEX); public static Matcher STRING_MATCHER = STRING_PATTERN.matcher(""); public static final String VAR_REGEX = "^\\$\\w+\\w*$"; public static final Pattern VAR_PATTERN = Pattern.compile(VAR_REGEX); public static Matcher VAR_MATCHER = VAR_PATTERN.matcher(""); public static final String NUM_REGEX = "^[1-9]+[0-9]*|0|\\.[0-9]+|[0-9]+\\.[0-9]+$"; public static final Pattern NUM_PATTERN = Pattern.compile(NUM_REGEX); public static Matcher NUM_MATCHER = NUM_PATTERN.matcher(""); 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 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(); }
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); } }
private void copy(File workspaceDir, InputStream in, Pattern glob, boolean overwrite) throws Exception { Jar jar = new Jar("dot", in); try { for (Entry<String, Resource> e : jar.getResources().entrySet()) { String path = e.getKey(); bnd.trace("path %s", path); if (glob != null && !glob.matcher(path).matches()) continue; Resource r = e.getValue(); File dest = Processor.getFile(workspaceDir, path); if (overwrite || !dest.isFile() || dest.lastModified() < r.lastModified() || r.lastModified() <= 0) { bnd.trace("copy %s to %s", path, dest); File dp = dest.getParentFile(); if (!dp.exists() && !dp.mkdirs()) { throw new IOException("Could not create directory " + dp); } IO.copy(r.openInputStream(), dest); } } } finally { jar.close(); } }
public static String getChrom(String chromName) { Matcher m = chromPattern.matcher(chromName); if (!m.matches()) { return chromName; } return m.group(1); }
public static String removePrimerLR(String pname) { Matcher m = primerLRPattern.matcher(pname); if (!m.matches()) { throw new IllegalArgumentException(pname); } return m.group(1); }
/** * Reads the file that specifies method calls that should be replaced by other method calls. The * file is of the form: * * <p>[regex] [orig-method-def] [new-method-name] * * <p>where the orig_method-def is of the form: * * <p>fully-qualified-method-name (args) * * <p>Blank lines and // comments are ignored. The orig-method-def is replaced by a call to * new-method-name with the same arguments in any classfile that matches the regular expressions. * All method names and argument types should be fully qualified. */ public void read_map_file(File map_file) throws IOException { LineNumberReader lr = new LineNumberReader(new FileReader(map_file)); MapFileError mfe = new MapFileError(lr, map_file); Pattern current_regex = null; Map<MethodDef, MethodInfo> map = new LinkedHashMap<MethodDef, MethodInfo>(); for (String line = lr.readLine(); line != null; line = lr.readLine()) { line = line.replaceFirst("//.*$", ""); if (line.trim().length() == 0) continue; if (line.startsWith(" ")) { if (current_regex == null) throw new IOException("No current class regex on line " + lr.getLineNumber()); StrTok st = new StrTok(line, mfe); st.stok.wordChars('.', '.'); MethodDef md = parse_method(st); String new_method = st.need_word(); map.put(md, new MethodInfo(new_method)); } else { if (current_regex != null) { MethodMapInfo mmi = new MethodMapInfo(current_regex, map); map_list.add(mmi); map = new LinkedHashMap<MethodDef, MethodInfo>(); } current_regex = Pattern.compile(line); } } if (current_regex != null) { MethodMapInfo mmi = new MethodMapInfo(current_regex, map); map_list.add(mmi); } dump_map_list(); }
public boolean accept(File pathname) { if (pathname.isDirectory()) { return true; } else { return pattern.matcher(pathname.getName()).matches(); } }
/** * 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); }
public static void main(String[] args) throws IOException { Path path = Paths.get("../alice.txt"); String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); Stream<String> words = Stream.of(contents.split("[\\P{L}]+")); show("words", words); Stream<String> song = Stream.of("gently", "down", "the", "stream"); show("song", song); Stream<String> silence = Stream.empty(); silence = Stream.<String>empty(); // Explicit type specification show("silence", silence); Stream<String> echos = Stream.generate(() -> "Echo"); show("echos", echos); Stream<Double> randoms = Stream.generate(Math::random); show("randoms", randoms); Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE)); show("integers", integers); Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents); show("wordsAnotherWay", wordsAnotherWay); try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) { show("lines", lines); } }
private String doCommands(String key, Link source) { String[] args = commands.split(key); if (args == null || args.length == 0) return null; for (int i = 0; i < args.length; i++) if (args[i].indexOf('\\') >= 0) args[i] = args[i].replaceAll("\\\\;", ";"); if (args[0].startsWith("^")) { String varname = args[0].substring(1).trim(); Processor parent = source.start.getParent(); if (parent != null) return parent.getProperty(varname); return null; } Processor rover = domain; while (rover != null) { String result = doCommand(rover, args[0], args); if (result != null) return result; rover = rover.getParent(); } for (int i = 0; targets != null && i < targets.length; i++) { String result = doCommand(targets[i], args[0], args); if (result != null) return result; } return doCommand(this, args[0], args); }