List of usage examples for java.util.regex Matcher groupCount
public int groupCount()
From source file:com.mapr.synth.samplers.VinSampler.java
private List<Integer> yearCodes(String years) { List<Integer> x = Lists.newArrayList(); for (String range : onComma.split(years)) { Matcher m = rangePattern.matcher(range); if (m.matches()) { if (m.groupCount() == 1) { x.add(Integer.parseInt(m.group(1))); } else { int start = Integer.parseInt(m.group(1)); int end = Integer.parseInt(m.group(2).substring(1)); for (int year = start; year <= end; year++) { x.add(Integer.parseInt(m.group(1))); }/* ww w . jav a 2 s . c o m*/ } } else { throw new IllegalArgumentException("Can't parse range " + range); } } return x; }
From source file:me.vertretungsplan.parser.BaseParser.java
String getClassName(String text, JSONObject data) throws JSONException { text = text.replace("(", "").replace(")", ""); if (data.has(PARAM_CLASS_REGEX)) { Pattern pattern = Pattern.compile(data.getString(PARAM_CLASS_REGEX)); Matcher matcher = pattern.matcher(text); if (matcher.find()) { if (matcher.groupCount() > 0) { return matcher.group(1); } else { return matcher.group(); }/*from w w w .ja v a2 s. c om*/ } else { return ""; } } else { return text; } }
From source file:gtu._work.ui.RegexTestUI.java
private void jText1OrJArea1Change(DocumentEvent doc) { try {// w w w . ja va2 s . c om String complie1 = regexText.getText(); String complie2 = regexText0.getText(); String complie = complie1; if (StringUtils.isBlank(complie1)) { complie = complie2; } String matcherStr = srcArea.getText(); if (StringUtils.isBlank(complie)) { setTitle("Regex"); return; } if (StringUtils.isBlank(matcherStr)) { setTitle("content"); return; } Pattern pattern = Pattern.compile(complie); Matcher matcher = pattern.matcher(matcherStr); DefaultComboBoxModel model1 = new DefaultComboBoxModel(); groupList.setModel(model1); while (matcher.find()) { model1.addElement("---------------------"); for (int ii = 0; ii <= matcher.groupCount(); ii++) { model1.addElement(ii + " : [" + matcher.group(ii) + "]"); } } DefaultComboBoxModel model2 = new DefaultComboBoxModel(); scannerList.setModel(model2); Scanner scanner = new Scanner(matcherStr); scanner.useDelimiter(pattern); while (scanner.hasNext()) { model2.addElement("[" + scanner.next() + "]"); } scanner.close(); this.setTitle("?"); } catch (Exception ex) { this.setTitle(ex.getMessage()); ex.printStackTrace(); } }
From source file:org.binding.openhab.samsungac.communicator.AirConditioner.java
/** * Handling of the responses is done by reading a response from the air conditioner, * until there's no more responses to read. This is because the air conditioner will * send us messages each time some presses the remote or some state of the air conditioner * changes./*from w w w.j a v a 2 s .c om*/ * * @param commandId An id of the command we are waiting for a response on. Not mandatory * @throws Exception Is thrown if we cannot parse the response from the air conditioner */ private void handleResponse(String commandId) throws Exception { String line; while ((line = readLine(socket)) != null) { logger.debug("Got response:'" + line + "'"); if (line == null || ResponseParser.isFirstLine(line)) { continue; } if (ResponseParser.isNotLoggedInResponse(line)) { if (TOKEN_STRING != null) { return; } writeLine("<Request Type=\"GetToken\" />"); continue; } if (ResponseParser.isFailedAuthenticationResponse(line)) { throw new Exception("failed to connect: '" + line + "'"); } if (commandId != null && ResponseParser.isCorrectCommandResponse(line, commandId)) { logger.debug("Correct command response: '" + line + "'"); continue; } if (ResponseParser.isResponseWithToken(line)) { TOKEN_STRING = ResponseParser.parseTokenFromResponse(line); logger.info("Received TOKEN from AC: '" + TOKEN_STRING + "'"); return; } if (ResponseParser.isReadyForTokenResponse(line)) { logger.info("NO TOKEN SET! Please switch off and on the air conditioner within 30 seconds"); return; } if (ResponseParser.isSuccessfulLoginResponse(line)) { logger.debug("SuccessfulLoginResponse: '" + line + "'"); return; } if (ResponseParser.isDeviceState(line)) { logger.debug("Response is device state '" + line + "'"); statusMap.clear(); statusMap = ResponseParser.parseStatusResponse(line); return; } if (ResponseParser.isDeviceControl(line)) { logger.debug("DeviceControl: '" + line + "'"); continue; } if (ResponseParser.isUpdateStatus(line)) { Pattern pattern = Pattern.compile("Attr ID=\"(.*)\" Value=\"(.*)\""); Matcher matcher = pattern.matcher(line); if (matcher.groupCount() == 2) { try { CommandEnum cmd = CommandEnum.valueOf(matcher.group(0)); if (cmd != null) { statusMap.put(cmd, matcher.group(1)); } } catch (IllegalStateException e) { } } continue; } } }
From source file:org.apache.nifi.processors.enrich.AbstractEnrichProcessor.java
/** * This method returns the parsed record string in the form of * a map of two strings, consisting of a iteration aware attribute * names and its values// w ww . j a v a 2 s.com * * @param recordPosition the iteration counter for the record * @param rawResult the raw query results to be parsed * @param queryParser The parsing mechanism being used to parse the data into groups * @param queryRegex The regex to be used to split the query results into groups * @return Map with attribute names and values */ protected Map<String, String> parseResponse(String recordPosition, String rawResult, String queryParser, String queryRegex, String schema) { Map<String, String> results = new HashMap<>(); Pattern p; recordPosition = StringUtils.isEmpty(recordPosition) ? "0" : recordPosition; // Iterates over the results using the QUERY_REGEX adding the captured groups // as it progresses switch (queryParser) { case "Split": // Time to Split the results... String[] splitResult = rawResult.split(queryRegex); for (int r = 0; r < splitResult.length; r++) { results.put("enrich." + schema + ".record" + recordPosition + ".group" + String.valueOf(r), splitResult[r]); } break; case "RegEx": // RegEx was chosen, iterating... p = Pattern.compile(queryRegex); Matcher finalResult = p.matcher(rawResult); if (finalResult.find()) { // Note that RegEx matches capture group 0 is usually broad but starting with it anyway // for the sake of purity for (int r = 0; r < finalResult.groupCount(); r++) { results.put("enrich." + schema + ".record" + recordPosition + ".group" + String.valueOf(r), finalResult.group(r)); } } break; case "None": // Fails to NONE default: // NONE was chosen, just appending the record result as group0 without further splitting results.put("enrich." + schema + ".record" + recordPosition + ".group0", rawResult); break; } return results; }
From source file:biz.astute.test.simulator.rest.RequestContext.java
/** * Return path portion of URL. The url may be modified to extract variables. * * @param globalProperties global properties * @return path portion of url/* w w w. j a v a 2s . c o m*/ * @throws UnsupportedEncodingException exception */ public final String getResourcePath(final Properties globalProperties) throws UnsupportedEncodingException { uriProperties.clear(); String requestURI = URLDecoder.decode(request.getRequestURI(), "utf-8"); Pattern[] currentPatterns = getPatterns(globalProperties); if (currentPatterns.length < 1) { return requestURI; } StringBuilder resourceName = new StringBuilder(requestURI); resourceName.append('/'); // Remove this later - need for matcher for (Pattern pattern : currentPatterns) { Matcher matcher = pattern.matcher(resourceName); if (matcher.matches() && (matcher.groupCount() > 0)) { for (int index = 1; index <= matcher.groupCount(); index++) { String matched = matcher.group(index); uriProperties.add(matched); } // Do so in reverse order so as to not affect offset for (int index = matcher.groupCount(); index > 0; index--) { resourceName.replace(matcher.start(index), matcher.end(index), StringUtils.EMPTY); } break; } } // remove '/' appended earlier resourceName.setLength(resourceName.length() - 1); // Remove any // that result from pattern replacement return resourceName.toString().replaceAll("//", "/"); }
From source file:org.apache.gobblin.hive.policy.HiveRegistrationPolicyBase.java
protected String getDatabaseOrTableName(Path path, String nameKey, String regexKey, Optional<Pattern> pattern) { String name;//from ww w . j a v a2 s.c o m if (this.props.contains(nameKey)) { name = this.props.getProp(nameKey); } else if (pattern.isPresent()) { Matcher matcher = pattern.get().matcher(path.toString()); if (matcher.matches() && matcher.groupCount() >= 1) { name = matcher.group(1); } else { throw new IllegalStateException("No group match found for regexKey " + regexKey + " with regexp " + pattern.get().toString() + " on path " + path); } } else { throw new IllegalStateException("Missing required property " + nameKey + " or " + regexKey); } return sanitizeAndValidateName(name); }
From source file:com.joliciel.talismane.tokeniser.filters.TokenRegexFilterImpl.java
@Override public void verify() { Pattern pattern = this.getPattern(); Matcher matcher = pattern.matcher(""); if (this.groupIndex > matcher.groupCount()) { throw new TalismaneException("No group " + this.groupIndex + " in pattern: " + this.regex); }/*w w w . j a va 2 s. c o m*/ }
From source file:guru.qas.martini.runtime.harness.MartiniCallable.java
protected Object[] getArguments(Step step, Method method, StepImplementation implementation) { Parameter[] parameters = method.getParameters(); Object[] arguments = new Object[parameters.length]; Map<String, String> exampleValues = null; Recipe recipe = martini.getRecipe(); ScenarioDefinition definition = recipe.getScenarioDefinition(); if (ScenarioOutline.class.isInstance(definition)) { exampleValues = new HashMap<>(); ScenarioOutline outline = ScenarioOutline.class.cast(definition); int exampleLine = recipe.getLocation().getLine(); List<Examples> examples = outline.getExamples(); TableRow header = null;/*from w w w .j a v a 2 s . c o m*/ TableRow match = null; for (Iterator<Examples> i = examples.iterator(); null == match && i.hasNext();) { Examples nextExamples = i.next(); List<TableRow> rows = nextExamples.getTableBody(); for (Iterator<TableRow> j = rows.iterator(); null == match && j.hasNext();) { TableRow row = j.next(); if (row.getLocation().getLine() == exampleLine) { match = row; header = nextExamples.getTableHeader(); } } } checkState(null != header, "unable to locate matching Examples table"); List<TableCell> headerCells = header.getCells(); List<TableCell> rowCells = match.getCells(); checkState(headerCells.size() == rowCells.size(), "Examples header to row size mismatch"); for (int i = 0; i < headerCells.size(); i++) { String headerValue = headerCells.get(i).getValue(); String rowValue = rowCells.get(i).getValue(); exampleValues.put(headerValue, rowValue); } } if (parameters.length > 0) { String text = step.getText(); Pattern pattern = implementation.getPattern(); Matcher matcher = pattern.matcher(text); checkState(matcher.find(), "unable to locate substitution parameters for pattern %s with input %s", pattern.pattern(), text); 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; if (null == exampleValues) { converted = conversionService.convert(parameterAsString, parameterType); } else { Matcher tableMatcher = OUTLINE_PATTERN.matcher(parameterAsString); checkState(tableMatcher.find(), "Example table keys must be in the format <key>"); String key = tableMatcher.group(1); String tableValue = exampleValues.get(key); converted = conversionService.convert(tableValue, parameterType); } arguments[i] = converted; } } return arguments; }
From source file:com.liferay.ide.project.core.tests.UpgradeLiferayProjectsOpTests.java
private String getNewDoctTypeSetting(String doctypeSetting, String regrex) { Pattern p = Pattern.compile(regrex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher m = p.matcher(doctypeSetting); if (m.find()) { return m.group(m.groupCount()); }//from www .ja v a 2s . c o m return null; }