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()); } }
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); }
/** * Import an XQuery library module from the given document. The namespace and preferred prefix of * the module are extracted from the module itself. The MIME type of the document is set to * "application/xquery" as a side-effect. * * @param module the non-XML document that holds the library module's source * @return this service, to chain calls * @throws DatabaseException if the module is an XML document, or the module declaration cannot be * found at the top of the document */ public QueryService importModule(Document module) { if (module instanceof XMLDocument) throw new DatabaseException("module cannot be an XML document: " + module); Matcher matcher = MODULE_DECLARATION_DQUOTE.matcher(module.contentsAsString()); if (!matcher.find()) { matcher = MODULE_DECLARATION_SQUOTE.matcher(module.contentsAsString()); if (!matcher.find()) throw new DatabaseException("couldn't find a module declaration at the top of " + module); } module.metadata().setMimeType("application/xquery"); String moduleNamespace = matcher.group(1); // TODO: should do URILiteral processing here to replace entity and character references and // normalize // whitespace, but since it seems that eXist doesn't do it either (bug?) there's no reason to // rush. Document prevModule = moduleMap.get(moduleNamespace); if (prevModule != null && !prevModule.equals(module)) throw new DatabaseException( "module " + moduleNamespace + " already bound to " + prevModule + ", can't rebind to " + module); moduleMap.put(moduleNamespace, module); return this; }
public String parse(String format) { StringBuffer buffer = new StringBuffer(); Matcher m = formatPattern.matcher(format); while (m.find()) m.appendReplacement(buffer, getFormatSpecifierValue(m.group())); m.appendTail(buffer); return buffer.toString(); }
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); }
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(); }
/** * 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; }
public void _sendString(String text) { if (writeCommand == null) return; /* intercept sessions -i and deliver it to a listener within armitage */ if (sessionListener != null) { Matcher m = interact.matcher(text); if (m.matches()) { sessionListener.actionPerformed(new ActionEvent(this, 0, m.group(1))); return; } } Map read = null; try { synchronized (this) { if (window != null && echo) { window.append(window.getPromptText() + text); } } if ("armitage.push".equals(writeCommand)) { read = (Map) connection.execute(writeCommand, new Object[] {session, text}); } else { connection.execute(writeCommand, new Object[] {session, text}); read = readResponse(); } processRead(read); fireSessionWroteEvent(text); } catch (Exception ex) { ex.printStackTrace(); } }
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 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(); }
private List<String> convertFollowupPatientIds(List<String> patientIds) { List<String> convertedPatientIds = new ArrayList<String>(); for (String patientId : patientIds) { Matcher patientIdMatcher = FOLLOW_UP_PATIENT_ID_REGEX.matcher(patientId); convertedPatientIds.add(patientIdMatcher.find() ? patientIdMatcher.group(1) : patientId); } return convertedPatientIds; }
public URLFinder(String text) { Matcher matcher = dfPattern.matcher(text); urls = new ArrayList<String>(); locations = new ArrayList<Integer[]>(); while (matcher.find()) { urls.add(matcher.group(1)); locations.add(new Integer[] {matcher.start(1), matcher.end(1)}); } }
public static void main(String[] args) throws PatternSyntaxException { Scanner in = new Scanner(System.in); System.out.println("Enter pattern: "); String patternString = in.nextLine(); Pattern pattern = Pattern.compile(patternString); while (true) { System.out.println("Enter string to match: "); String input = in.nextLine(); if (input == null || input.equals("")) return; Matcher matcher = pattern.matcher(input); if (matcher.matches()) { System.out.println("Match"); int g = matcher.groupCount(); if (g > 0) { for (int i = 0; i < input.length(); i++) { // Print any empty groups for (int j = 1; j <= g; j++) if (i == matcher.start(j) && i == matcher.end(j)) System.out.print("()"); // Print ( for non-empty groups starting here for (int j = 1; j <= g; j++) if (i == matcher.start(j) && i != matcher.end(j)) System.out.print('('); System.out.print(input.charAt(i)); // Print ) for non-empty groups ending here for (int j = 1; j <= g; j++) if (i + 1 != matcher.start(j) && i + 1 == matcher.end(j)) System.out.print(')'); } System.out.println(); } } else System.out.println("No match"); } }
// 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(); }
protected RichText.Part text(PState s, String text, Map<? extends Attribute, ?> attrs) throws IOException { RichText.Part ret = null; int p = 0; while (true) { Matcher m = urlpat.matcher(text); if (!m.find(p)) break; URL url; try { String su = text.substring(m.start(), m.end()); if (su.indexOf(':') < 0) su = "http://" + su; url = new URL(su); } catch (java.net.MalformedURLException e) { p = m.end(); continue; } RichText.Part lead = new RichText.TextPart(text.substring(0, m.start()), attrs); if (ret == null) ret = lead; else ret.append(lead); Map<Attribute, Object> na = new HashMap<Attribute, Object>(attrs); na.putAll(urlstyle); na.put(ChatAttribute.HYPERLINK, new FuckMeGentlyWithAChainsaw(url)); ret.append(new RichText.TextPart(text.substring(m.start(), m.end()), na)); p = m.end(); } if (ret == null) ret = new RichText.TextPart(text, attrs); else ret.append(new RichText.TextPart(text.substring(p), attrs)); return (ret); }
// 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 String getResult() { if (result != null) { return result; } matcher = RESULT_PATTERN.matcher(firstLine); if (matcher.find()) { result = matcher.group(1); } return result; }
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 ControllerRequest(Class<? extends Controller> controllerClass, Matcher matchedUrl) { this.controllerClass = controllerClass; if (matchedUrl.groupCount() > 0) { List<String> argsList = new ArrayList<String>(matchedUrl.groupCount()); for (int i = 1; i <= matchedUrl.groupCount(); i++) { argsList.add(matchedUrl.group(i)); } this.args = argsList; } else { this.args = new ArrayList<String>(0); } }
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); } }
/** * Strips all non-article links from the given markup; anything like [[this]] is removed unless it * goes to a wikipedia article, redirect, or disambiguation page. * * @param markup the text to be stripped * @return the stripped text */ public static String stripIsolatedLinks(String markup) { Vector<Integer> linkStack = new Vector<Integer>(); Pattern p = Pattern.compile("(\\[\\[|\\]\\])"); Matcher m = p.matcher(markup); StringBuffer sb = new StringBuffer(); int lastIndex = 0; while (m.find()) { String tag = markup.substring(m.start(), m.end()); if (tag.equals("[[")) linkStack.add(m.start()); else { if (!linkStack.isEmpty()) { int linkStart = linkStack.lastElement(); linkStack.remove(linkStack.size() - 1); if (linkStack.isEmpty()) { sb.append(markup.substring(lastIndex, linkStart)); // we have the whole link, with other links nested inside if it's an image String linkMarkup = markup.substring(linkStart + 2, m.start()); // System.out.println(" - " + linkStart + ", " + m.end() + ", " + markup.length()) ; if (markup.substring(Math.max(0, linkStart - 10), linkStart).matches("(?s).*(\\W*)\n") && (m.end() >= markup.length() - 1 || markup .substring(m.end(), Math.min(markup.length() - 1, m.end() + 10)) .matches("(?s)(\\W*)(\n.*|$)"))) { // discarding link } else { sb.append("[["); sb.append(linkMarkup); sb.append("]]"); } lastIndex = m.end(); } } } } if (!linkStack.isEmpty()) System.err.println( "MarkupStripper | Warning: links were not well formed, so we cannot guarantee that they were stripped out correctly. "); sb.append(markup.substring(lastIndex)); return sb.toString(); }
/** * Initializes the date format. * * @param d input * @param e example format * @param ii input info * @throws QueryException query exception */ final void date(final byte[] d, final String e, final InputInfo ii) throws QueryException { final Matcher mt = DATE.matcher(Token.string(d).trim()); if (!mt.matches()) throw dateError(d, e, ii); yea = toLong(mt.group(1), false, ii); // +1 is added to BC values to simplify computations if (yea < 0) yea++; mon = (byte) (Strings.toInt(mt.group(3)) - 1); day = (byte) (Strings.toInt(mt.group(4)) - 1); if (mon < 0 || mon >= 12 || day < 0 || day >= dpm(yea, mon)) throw dateError(d, e, ii); if (yea <= MIN_YEAR || yea > MAX_YEAR) throw DATERANGE_X_X.get(ii, type, chop(d, ii)); zone(mt, 5, d, ii); }
/** * 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; }
@Override public StorageResults fetch(Expression userQuery) { Expression expression = userQuery.normalize(); Matcher matcher = expression.accept(new MatcherCreator()); List<DataRecord> matchRecords = new LinkedList<DataRecord>(); for (DataRecord dataRecord : storage) { if (matcher.match(dataRecord)) { matchRecords.add(dataRecord); } } List<DataRecord> filteredRecords = expression.accept(new Filter(matchRecords)); return new InMemoryStorageResults(filteredRecords); }