List of usage examples for java.util.regex Matcher groupCount
public int groupCount()
From source file:com.bluexml.side.portal.alfresco.reverse.reverser.LayoutReverser.java
public void readAttributes(Map<String, String> properties, String string, int groupId, int groupValue) { Pattern regexpDiv = Pattern.compile(string); Matcher matcher = regexpDiv.matcher(currentLine); while (matcher.find()) { // System.out.println("MATCHS"); String group = matcher.group(); // System.out.println("\tgroup:" + group); int groupCount = matcher.groupCount(); for (int i = 0; i <= groupCount; i++) { String group2 = matcher.group(i); // System.out.println("\tgroup (" + i + "):" + group2); }/*from w w w. j av a 2s. c o m*/ String attId = matcher.group(groupId); String attvalue = matcher.group(groupValue); properties.put(attId, attvalue); } }
From source file:br.com.blackhubos.eventozero.util.Framework.java
/** * Converte a String feita do fromLocation(Location) devolta para uma localizao. * * @param serial O serial obtido no mtodo que transformou anteriormente a localizao em String. * @return retorna a Localizao convertida. *///from ww w. ja v a2 s. c o m public static Location toLocation(final String serial) { final Pattern pattern = Pattern.compile( "^World\\s*\\[([a-zA-Z0-9_-]+)\\]\\s*X\\s*\\[([0-9]+)\\]\\s*Y\\s*\\[([0-9]+)\\]\\s*Z\\s*\\[([0-9]+)\\](\\s*Yaw\\s*\\[([0-9\\.]+)\\]\\s*Pitch\\s*\\[([0-9\\.]+)\\])?"); final Matcher m = pattern.matcher(serial); if (m.matches()) { if ((m.groupCount() >= 5) && (m.group(5) != null) && (m.group(6) != null) && (m.group(7) != null)) { return new Location(Framework.getWorld(m.group(1)), Framework.getInt(m.group(2)), Framework.getInt(m.group(3)), Framework.getInt(m.group(4)), Framework.getFloat(m.group(6)), Framework.getFloat(m.group(7))); } else { return new Location(Framework.getWorld(m.group(1)), Framework.getInt(m.group(2)), Framework.getInt(m.group(3)), Framework.getInt(m.group(4))); } } else { return null; } }
From source file:com.isecpartners.gizmo.FourthIdea.java
private String apply_macros(String command_string) { if (command_translation == null) return command_string; for (Object obj : command_translation.keySet()) { String key = (String) obj; String value = (String) command_translation.get(key); String regex = "^([\\s]*\\" + key + ").*"; // so the goal here is to substitute the pattern *only* if it shows up first // and ignore trailing spaces. i want to take the first group, remove that // and then prepend the replacement string to what's left. Matcher match = Pattern.compile(regex).matcher(command_string); if (match.matches()) { if (match.groupCount() != 1) break; String found_str = match.group(1); int end_of_match = command_string.indexOf(found_str) + found_str.length(); command_string = value + " " + command_string.substring(end_of_match + 1); }//w ww. java 2s .co m command_string = Pattern.compile(key).matcher(command_string).replaceAll(value); } return command_string; }
From source file:br.com.blackhubos.eventozero.util.Framework.java
public static void printGroups(final Pattern pattern, final String literal) { final Matcher matcher = pattern.matcher(literal); if (matcher.find()) { for (int i = 1; i <= matcher.groupCount(); i++) { System.out.println("Group " + i + ": \"" + (matcher.group(i) != null ? matcher.group(i) : "(no encontrado)") + "\""); }//from ww w.ja v a 2s .c o m } }
From source file:fr.smile.liferay.LiferayUrlRewriter.java
/** * Fix all resources urls and return the result. * * @param input The original charSequence to be processed. * @param requestUrl The request URL.// ww w.j a v a2 s .c o m * @param baseUrlParam The base URL selected for this request. * @return the result of this renderer. */ public CharSequence rewriteHtml(CharSequence input, String requestUrl, Pattern pattern, String baseUrlParam, String visibleBaseUrl) { if (LOG.isDebugEnabled()) { LOG.debug("input=" + input); LOG.debug("rewriteHtml (requestUrl=" + requestUrl + ", pattern=" + pattern + ",baseUrlParam)" + baseUrlParam + ",strVisibleBaseUrl=" + visibleBaseUrl + ")"); } StringBuffer result = new StringBuffer(input.length()); Matcher m = pattern.matcher(input); while (m.find()) { if (LOG.isTraceEnabled()) { LOG.trace("found match: " + m); } String url = input.subSequence(m.start(3) + 1, m.end(3) - 1).toString(); url = rewriteUrl(url, requestUrl, baseUrlParam, visibleBaseUrl); url = url.replaceAll("\\$", "\\\\\\$"); // replace '$' -> '\$' as it // denotes group StringBuffer tagReplacement = new StringBuffer("<$1$2=\"").append(url).append("\""); if (m.groupCount() > 3) { tagReplacement.append("$4"); } tagReplacement.append('>'); if (LOG.isTraceEnabled()) { LOG.trace("replacement: " + tagReplacement); } m.appendReplacement(result, tagReplacement.toString()); } m.appendTail(result); return result; }
From source file:guru.qas.martini.jmeter.sampler.MartiniSampler.java
protected SampleResult getSubResult(Step step, Method method, Pattern pattern) { String label = getLabel(step); SampleResult result = new SampleResult(); result.setSuccessful(true);/*from www . ja v a2 s .com*/ result.sampleStart(); SamplerContext samplerContext = new SamplerContext(super.getThreadContext()); try { ApplicationContext applicationContext = this.getApplicationContext(); Parameter[] parameters = method.getParameters(); Object[] arguments = new Object[parameters.length]; if (parameters.length > 0) { String text = step.getText(); Matcher matcher = pattern.matcher(text); checkState(matcher.find(), "unable to locate substitution parameters for pattern %s with input %s", pattern.pattern(), text); ConversionService conversionService = applicationContext.getBean(ConversionService.class); int groupCount = matcher.groupCount(); for (int i = 0; i < groupCount; i++) { String parameterAsString = matcher.group(i + 1); Parameter parameter = parameters[i]; Class<?> parameterType = parameter.getType(); Object converted = conversionService.convert(parameterAsString, parameterType); arguments[i] = converted; } } samplerContext.setStatus(Status.PASSED); Class<?> declaringClass = method.getDeclaringClass(); Object bean = applicationContext.getBean(declaringClass); Object returnValue = method.invoke(bean, arguments); if (HttpEntity.class.isInstance(returnValue)) { HttpEntity entity = HttpEntity.class.cast(returnValue); samplerContext.setHttpEntities(Collections.singleton(entity)); } } catch (Exception e) { samplerContext.setStatus(Status.FAILED); samplerContext.setException(e); result.setSuccessful(false); label = "FAIL: " + label; } finally { result.sampleEnd(); result.setSampleLabel(label); } return result; }
From source file:gtu._work.ui.RegexCatchReplacer_Ebao.java
/** * @param fromPattern//ww w . j a va 2 s . c o m * ???pattern * @param toFormat * ??pattern * @param replaceText * ?? */ void replacer(String fromPattern, String toFormat, String replaceText) { try { Pattern pattern = Pattern.compile(fromPattern); Matcher matcher = pattern.matcher(replaceText); Map<String, Integer> tmap = new LinkedHashMap<String, Integer>(); String tempStr = null; for (; matcher.find();) { tempStr = toFormat.toString(); for (int ii = 0; ii <= matcher.groupCount(); ii++) { System.out.println(ii + " -- " + matcher.group(ii)); tempStr = tempStr.replaceAll("#" + ii + "#", Matcher.quoteReplacement(matcher.group(ii))); if (!tmap.containsKey(tempStr)) { tmap.put(tempStr, 0); } tmap.put(tempStr, tmap.get(tempStr) + 1); } } DefaultTableModel model = JTableUtil.createModel(true, "match", "count"); for (String str : tmap.keySet()) { model.addRow(new Object[] { str, tmap.get(str) }); } setTitle("total : " + model.getRowCount()); resultArea.setModel(model); // ebao? JTableUtil resultAreaUtil = JTableUtil.newInstance(resultArea); DefaultTableModel model2 = JTableUtil.createModel(true, "msgId", "Label"); boolean isExactSearch = exactEbaoSearchChk.isSelected(); ebaoTable.setModel(model2); for (int ii = 0; ii < model.getRowCount(); ii++) { String msgId = (String) resultAreaUtil.getRealValueAt(ii, 0); callEbaoMsgId(msgId, isExactSearch); } } catch (Exception ex) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(), getTitle()); ex.printStackTrace(); } }
From source file:org.commoncrawl.mapred.pipelineV3.domainmeta.blogs.postfrequency.ScanDatabaseStep.java
@Override public void map(TextBytes key, TextBytes jsonMetadata, OutputCollector<TextBytes, HitsByMonth> collector, Reporter reporter) throws IOException { String url = key.toString();//w w w . j a va2s . c om Matcher topLevelMatcher = topLevelBlogPattern.matcher(url); Matcher nestedBlogMatcher = nestedBlogPattern.matcher(url); Matcher indexHTMLBlogMatcher = indexHTMLBlogPattern.matcher(url); Matcher indexBlogMatcher = indexBlogPattern.matcher(url); Matcher nestedIndexHTMLBlogMatcher = nestedIndexHTMLBlogPattern.matcher(url); Matcher nestedIndexBlogMatcher = nestedIndexBlogPattern.matcher(url); Matcher tumblrPostMatcher = tumblrStyleBlogPattern.matcher(url); if (indexHTMLBlogMatcher.matches() && indexHTMLBlogMatcher.groupCount() >= 1) { reporter.incrCounter(Counters.MATCHED_INDEX_HTML_PATTERN, 1); HitsByMonth hits = new HitsByMonth(); hits.setFlags(PostFrequencyInfo.Flags.HAS_INDEX_HTML_AFTER_DATE); collector.collect(new TextBytes("http://" + indexHTMLBlogMatcher.group(1) + "/"), hits); } else if (indexBlogMatcher.matches() && indexBlogMatcher.groupCount() >= 1) { reporter.incrCounter(Counters.MATCHED_INDEX_PATTERN, 1); HitsByMonth hits = new HitsByMonth(); hits.setFlags(PostFrequencyInfo.Flags.HAS_YEAR_MONTH_SLASH_INDEX); collector.collect(new TextBytes("http://" + indexBlogMatcher.group(1) + "/"), hits); } else if (nestedIndexHTMLBlogMatcher.matches() && nestedIndexHTMLBlogMatcher.groupCount() >= 2) { reporter.incrCounter(Counters.MATCHED_NESTED_INDEX_HTML_PATTERN, 1); HitsByMonth hits = new HitsByMonth(); hits.setFlags(PostFrequencyInfo.Flags.HAS_INDEX_HTML_AFTER_DATE); collector.collect(new TextBytes("http://" + nestedIndexHTMLBlogMatcher.group(1) + "/" + nestedIndexHTMLBlogMatcher.group(2) + "/"), hits); } else if (nestedIndexBlogMatcher.matches() && nestedIndexBlogMatcher.groupCount() >= 2) { reporter.incrCounter(Counters.MATCHED_NESTED_INDEX_PATTERN, 1); HitsByMonth hits = new HitsByMonth(); hits.setFlags(PostFrequencyInfo.Flags.HAS_YEAR_MONTH_SLASH_INDEX); collector.collect(new TextBytes( "http://" + nestedIndexBlogMatcher.group(1) + "/" + nestedIndexBlogMatcher.group(2) + "/"), hits); } else if (tumblrPostMatcher.matches() && tumblrPostMatcher.groupCount() >= 2) { reporter.incrCounter(Counters.MATCHED_TUMBLR_BLOG_POST_PATTERN, 1); String uniqueURL = new String("http://" + tumblrPostMatcher.group(1) + "/"); try { // HACK long postId = Long.parseLong(tumblrPostMatcher.group(2)); long relativeMonth = postId / 1000000000L; Date dateStart = new Date(110, 6, 1); Date dateOfPost = new Date(dateStart.getTime() + (relativeMonth * 30 * 24 * 60 * 60 * 1000)); HitsByMonth hits = new HitsByMonth(); hits.setHitCount(1); hits.setYear(dateOfPost.getYear() + 1900); hits.setMonth(dateOfPost.getMonth() + 1); collector.collect(new TextBytes(uniqueURL), hits); } catch (Exception e) { reporter.incrCounter(Counters.CAUGHT_EXCEPTION_DURING_TUMBLR_POST_PARSE, 1); LOG.error("Exception parsing url:" + url + " Exception:" + StringUtils.stringifyException(e)); } } else if (topLevelMatcher.matches() && topLevelMatcher.groupCount() >= 3) { reporter.incrCounter(Counters.MATCHED_TOP_LEVEL_POST_PATTERN, 1); String uniqueURL = new String("http://" + topLevelMatcher.group(1) + "/"); int year = Integer.parseInt(topLevelMatcher.group(2)); int month = Integer.parseInt(topLevelMatcher.group(3)); HitsByMonth hits = new HitsByMonth(); hits.setHitCount(1); hits.setYear(year); hits.setMonth(month); hits.setFlags(scanForGenerator(key, jsonMetadata, reporter)); collector.collect(new TextBytes(uniqueURL), hits); } else if (nestedBlogMatcher.matches() && nestedBlogMatcher.groupCount() >= 4) { reporter.incrCounter(Counters.MATCHED_NESTED_POST_PATTERN, 1); if (!nestedBlogMatcher.group(1).endsWith("tumblr.com")) { String uniqueURL = new String( "http://" + nestedBlogMatcher.group(1) + "/" + nestedBlogMatcher.group(2) + "/"); int year = Integer.parseInt(nestedBlogMatcher.group(3)); int month = Integer.parseInt(nestedBlogMatcher.group(4)); HitsByMonth hits = new HitsByMonth(); hits.setHitCount(1); hits.setYear(year); hits.setMonth(month); hits.setFlags(scanForGenerator(key, jsonMetadata, reporter)); collector.collect(new TextBytes(uniqueURL), hits); } } }
From source file:net.sf.logsaw.dialect.websphere.WebsphereDialect.java
@Override public void parse(ILogResource log, InputStream input, ILogEntryCollector collector) throws CoreException { Assert.isNotNull(log, "log"); //$NON-NLS-1$ Assert.isNotNull(input, "input"); //$NON-NLS-1$ Assert.isNotNull(collector, "collector"); //$NON-NLS-1$ Assert.isTrue(isConfigured(), "Dialect should be configured by now"); //$NON-NLS-1$ try {/*from w ww .java 2s . co m*/ LogEntry currentEntry = null; IHasEncoding enc = (IHasEncoding) log.getAdapter(IHasEncoding.class); IHasLocale loc = (IHasLocale) log.getAdapter(IHasLocale.class); // WebSphere Dialect doesn't need to care about the timezone, because it is encoded in the log messages DateFormat df = getDateFormat(loc.getLocale()); LineIterator iter = IOUtils.lineIterator(input, enc.getEncoding()); int lineNo = 0; try { while (iter.hasNext()) { // Error handling lineNo++; List<IStatus> statuses = null; boolean fatal = false; // determines whether to interrupt parsing String line = iter.nextLine(); Matcher m = getInternalPattern().matcher(line); if (m.find()) { // The next line matches, so flush the previous entry and continue if (currentEntry != null) { collector.collect(currentEntry); currentEntry = null; } currentEntry = new LogEntry(); for (int i = 0; i < m.groupCount(); i++) { try { extractField(currentEntry, i + 1, m.group(i + 1), df); } catch (CoreException e) { // Mark for interruption fatal = fatal || e.getStatus().matches(IStatus.ERROR); // Messages will be displayed later if (statuses == null) { statuses = new ArrayList<IStatus>(); } if (e.getStatus().isMultiStatus()) { Collections.addAll(statuses, e.getStatus().getChildren()); } else { statuses.add(e.getStatus()); } } } // We encountered errors or warnings if (statuses != null && !statuses.isEmpty()) { currentEntry = null; // Stop propagation IStatus status = new MultiStatus(WebsphereDialectPlugin.PLUGIN_ID, 0, statuses.toArray(new IStatus[statuses.size()]), NLS.bind(Messages.WebsphereDialect_error_failedToParseLine, lineNo), null); if (fatal) { // Interrupt parsing in case of error throw new CoreException(status); } else { collector.addMessage(status); } } } else if (currentEntry != null) { // Append to message String msg = currentEntry.get(getFieldProvider().getMessageField()); StringWriter strWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(strWriter); printWriter.print(msg); printWriter.println(); printWriter.print(line); currentEntry.put(getFieldProvider().getMessageField(), strWriter.toString()); } if (collector.isCanceled()) { // Cancel parsing break; } } if (currentEntry != null) { // Collect left over entry collector.collect(currentEntry); } } finally { LineIterator.closeQuietly(iter); } } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, WebsphereDialectPlugin.PLUGIN_ID, NLS.bind(Messages.WebsphereDialect_error_failedToParseFile, new Object[] { log.getName(), e.getLocalizedMessage() }), e)); } }
From source file:com.cdd.bao.importer.KeywordMapping.java
public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache) throws JSONException, IOException { String uniqueID = null;// w w w . j a v a2 s . c o m List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>(); List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>(); Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>(); JSONArray jsonAnnot = new JSONArray(); final String SEP = "::"; // assertions: these always supply a term for (Assertion asrt : assertions) { JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest))); obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI)); jsonAnnot.put(obj); String hash = asrt.propURI + SEP + asrt.valueURI + SEP + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest)); gotAnnot.add(hash); } // go through the columns one at a time for (String key : keydata.keySet()) { String data = keydata.getString(key); Identifier id = findIdentifier(key); if (id != null) { if (uniqueID == null) uniqueID = id.prefix + data; continue; } TextBlock tblk = findTextBlock(key); if (tblk != null) { if (Util.isBlank(tblk.title)) linesTitle.add(data); else linesBlock.add(tblk.title + ": " + data); } Value val = findValue(key, data); if (val != null) { if (Util.isBlank(val.valueURI)) { linesSkipped.add(key + ": " + data); } else { String hash = val.propURI + SEP + val.valueURI + SEP + (val.groupNest == null ? "" : String.join(SEP, val.groupNest)); if (gotAnnot.contains(hash)) continue; JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(val.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest))); obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI)); jsonAnnot.put(obj); gotAnnot.add(hash); linesProcessed.add(key + ": " + data); } continue; } Literal lit = findLiteral(key, data); if (lit != null) { String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest)) + SEP + data; if (gotLiteral.contains(hash)) continue; JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(lit.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest))); obj.put("valueLabel", data); jsonAnnot.put(obj); gotLiteral.add(hash); linesProcessed.add(key + ": " + data); continue; } Reference ref = findReference(key, data); if (ref != null) { Pattern ptn = Pattern.compile(ref.valueRegex); Matcher m = ptn.matcher(data); if (!m.matches() || m.groupCount() < 1) throw new IOException( "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group."); JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(ref.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest))); obj.put("valueLabel", ref.prefix + m.group(1)); jsonAnnot.put(obj); linesProcessed.add(key + ": " + data); continue; } // probably shouldn't get this far, but just in case linesSkipped.add(key + ": " + data); } // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes for (int n = 0; n < jsonAnnot.length(); n++) { JSONObject obj = jsonAnnot.getJSONObject(n); String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI"); if (valueURI == null) continue; String[] groupNest = obj.getJSONArray("groupNest").toStringArray(); Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI), groupNest); if (assnList.length == 0) continue; SchemaTree tree = treeCache.get(assnList[0]); if (tree == null) continue; Set<String> exclusion = new HashSet<>(); for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent) exclusion.add(node.uri); if (exclusion.size() == 0) continue; for (int i = jsonAnnot.length() - 1; i >= 0; i--) if (i != n) { obj = jsonAnnot.getJSONObject(i); if (!obj.has("valueURI")) continue; if (!propURI.equals(obj.getString("propURI"))) continue; if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray())) continue; if (!exclusion.contains(obj.getString("valueURI"))) continue; jsonAnnot.remove(i); } } /*String text = ""; if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n"; if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n"; text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/ List<String> sections = new ArrayList<>(); if (linesTitle.size() > 0) sections.add(String.join(" / ", linesTitle)); if (linesBlock.size() > 0) sections.add(String.join("\n", linesBlock)); sections.add("#### IMPORTED ####"); if (linesSkipped.size() > 0) sections.add("SKIPPED:\n" + String.join("\n", linesSkipped)); if (linesProcessed.size() > 0) sections.add("PROCESSED:\n" + String.join("\n", linesProcessed)); String text = String.join("\n\n", sections); JSONObject assay = new JSONObject(); assay.put("uniqueID", uniqueID); assay.put("text", text); assay.put("schemaURI", schema.getSchemaPrefix()); assay.put("annotations", jsonAnnot); return assay; }