Java Code Examples for com.google.re2j.Matcher#group()

The following examples show how to use com.google.re2j.Matcher#group() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SqlTemplate.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the freshly substituted SQL code.
 *
 * @throws IllegalArgumentException if any substitution variable is not found in the template,
 *         or if there are any variable-like strings (%something%) left after substitution.
 */
public String build() {
  StringBuffer result = new StringBuffer(template.length());
  Set<String> found = new HashSet<>();
  Matcher matcher = SEARCH_PATTERN.matcher(template);
  while (matcher.find()) {
    String wholeMatch = matcher.group(0);
    String leftQuote = matcher.group(1);
    String key = matcher.group(2);
    String rightQuote = matcher.group(3);
    String value = substitutions.get(key);
    checkArgumentNotNull(value, "%%s% found in template but no substitution specified", key);
    checkArgument(leftQuote.equals(rightQuote), "Quote mismatch: %s", wholeMatch);
    matcher.appendReplacement(result, String.format("%s%s%s", leftQuote, value, rightQuote));
    found.add(key);
  }
  matcher.appendTail(result);
  Set<String> remaining = difference(substitutions.keySet(), found);
  checkArgument(remaining.isEmpty(),
      "Not found in template: %s", Joiner.on(", ").join(remaining));
  return result.toString();
}
 
Example 2
Source File: TestGhcnm.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static private int parseLine(String line) {
  int balony = 0;
  Matcher matcher = dataPattern.matcher(line);
  if (matcher.matches()) {
    for (int i = 1; i <= matcher.groupCount(); i++) {
      String r = matcher.group(i);
      if (r == null)
        continue;
      int value = (int) Long.parseLong(r.trim());
      balony += value;
    }
  } else {
    System.out.printf("Fail on %s%n", line);
  }
  return balony;
}
 
Example 3
Source File: ProxyHttpTransparent.java    From PacketProxy with Apache License 2.0 6 votes vote down vote up
private HostPort parseHostName(byte[] buffer) throws Exception {
	int start = 0;
	if ((start = StringUtils.binaryFind(buffer, "Host:".getBytes())) > 0) {
		start += 5;
	} else if ((start = StringUtils.binaryFind(buffer, "host:".getBytes())) > 0) {
		start += 5;
	} else {
		throw new Exception("Host: header field is not found in beginning of 4096 bytes of packets.");
	}
	int end = StringUtils.binaryFind(buffer, "\n".getBytes(), start);
	String serverCand = new String(ArrayUtils.subarray(buffer, start, end));
	String server = "";
	int port = 80;
	Pattern pattern = Pattern.compile("^ *([^:\n\r]+)(?::([0-9]+))?");
	Matcher matcher = pattern.matcher(serverCand);
	if (matcher.find()) {
		if (matcher.group(1) != null)
			server = matcher.group(1);
		if (matcher.group(2) != null)
			port = Integer.parseInt(matcher.group(2));
	} else {
		throw new Exception("Host: header field format is not recognized.");
	}
	return new HostPort(server, port);
}
 
Example 4
Source File: GempakParameterTable.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the parameter for the given name
 *
 * @param name name of the parameter (eg:, TMPK);
 * @return corresponding parameter or null if not found in table
 */
public GempakParameter getParameter(String name) {
  GempakParameter param = paramMap.get(name);
  if (param == null) { // try the regex list
    Set<String> keys = templateParamMap.keySet();
    if (!keys.isEmpty()) {
      for (String key : keys) {
        Pattern p = Pattern.compile(key);
        Matcher m = p.matcher(name);
        if (m.matches()) {
          String value = m.group(1);
          GempakParameter match = templateParamMap.get(key);
          param = new GempakParameter(match.getNumber(), name, match.getDescription() + " (" + value + " hour)",
              match.getUnit(), match.getDecimalScale());
          paramMap.put(name, param);
          break;
        }
      }
    }
  }
  return param;
}
 
Example 5
Source File: Https.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
public static String getCommonName(InetSocketAddress addr) throws Exception {
	SSLSocketFactory ssf = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(addr.getAddress(), addr.getPort());
    socket.startHandshake();
    SSLSession session = socket.getSession();
    X509Certificate[] servercerts = (X509Certificate[]) session.getPeerCertificates();

    Pattern pattern = Pattern.compile("CN=([^,]+)", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(servercerts[0].getSubjectDN().getName());
    if (matcher.find()) {
    	return matcher.group(1);
    }
    return "";
}
 
Example 6
Source File: GerritIntegrateLabel.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Nullable
static GerritIntegrateLabel parse(String str, GitRepository repository,
    GeneralOptions generalOptions) {
  Matcher matcher = LABEL_PATTERN.matcher(str);
  return matcher.matches()
         ? new GerritIntegrateLabel(repository, generalOptions,
                                    matcher.group(1),
                                    Integer.parseInt(matcher.group(2)),
                                    (matcher.group(3) == null
                                     ? null
                                     : Integer.parseInt(matcher.group(3))),
                                    matcher.group(4))
         : null;
}
 
Example 7
Source File: IdnTable.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Read the codepoint from a single line. The expected format of each line is:
 * {@code U+XXXX}
 * Where {@code XXXX} holds the hex value of the codepoint.
 */
private static int readCodepoint(String line) {
  Matcher matcher = LINE_PATTERN.matcher(line);
  checkArgument(matcher.lookingAt(), "Can't parse line: %s", line);

  String hexString = matcher.group(1);
  return Integer.parseInt(hexString, 16);
}
 
Example 8
Source File: Re2jRegexDeserializer.java    From bender with Apache License 2.0 5 votes vote down vote up
@Override
public DeserializedEvent deserialize(String raw) {
  Matcher m = this.pattern.matcher(raw);

  if (!m.matches()) {
    throw new DeserializationException("raw event does not match string");
  }

  int groups = m.groupCount();
  JsonObject obj = new JsonObject();
  for (int i = 0; i < groups && i < fields.size(); i++) {
    String str = m.group(i + 1);

    ReFieldConfig field = this.fields.get(i);

    switch (field.getType()) {
      case BOOLEAN:
        obj.addProperty(field.getName(), Boolean.parseBoolean(str));
        break;
      case NUMBER:
        obj.addProperty(field.getName(), NumberUtils.createNumber(str));
        break;
      case STRING:
        obj.addProperty(field.getName(), str);
        break;
      default:
        obj.addProperty(field.getName(), str);
        break;
    }
  }

  return new GenericJsonEvent(obj);
}
 
Example 9
Source File: Re2JRegexp.java    From presto with Apache License 2.0 5 votes vote down vote up
public Slice extract(Slice source, long groupIndex)
{
    Matcher matcher = re2jPattern.matcher(source);
    int group = toIntExact(groupIndex);
    validateGroup(group, matcher.groupCount());

    if (!matcher.find()) {
        return null;
    }

    return matcher.group(group);
}
 
Example 10
Source File: Scanner.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static String extractWMO(String header) {
  Matcher matcher = wmoPattern.matcher(header);
  if (!matcher.matches()) {
    // out.format("***header failed= %s%n", header);
    return null;
  }
  return matcher.group(1);
}
 
Example 11
Source File: Message.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String extractWMO() {
  Matcher matcher = wmoPattern.matcher(header);
  if (!matcher.matches()) {
    return "";
  }
  return matcher.group(1);
}
 
Example 12
Source File: GitRepository.java    From copybara with Apache License 2.0 5 votes vote down vote up
ImmutableList<TreeElement> lsTree(GitRevision reference, @Nullable String treeish,
    boolean recursive, boolean fullName)
    throws RepoException {
  ImmutableList.Builder<TreeElement> result = ImmutableList.builder();
  List<String> args = Lists.newArrayList("ls-tree", reference.getSha1());
  if (recursive) {
    args.add("-r");
  }
  if (fullName) {
    args.add("--full-name");
  }
  if (treeish != null) {
    args.add("--");
    args.add(treeish);
  }
  String stdout = simpleCommand(args).getStdout();
  for (String line : Splitter.on('\n').split(stdout)) {
    if (line.isEmpty()) {
      continue;
    }
    Matcher matcher = LS_TREE_ELEMENT.matcher(line);
    if (!matcher.matches()) {
      throw new RepoException("Unexpected format for ls-tree output: " + line);
    }
    // We ignore the mode for now
    GitObjectType objectType = GitObjectType.valueOf(matcher.group(2).toUpperCase());
    String sha1 = matcher.group(3);
    String path = matcher.group(4)
        // Per ls-tree documentation. Replace those escaped characters.
        .replace("\\\\", "\\").replace("\\t", "\t").replace("\\n", "\n");

    result.add(new TreeElement(objectType, sha1, path));
  }
  return result.build();
}
 
Example 13
Source File: AppEngineConnection.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Returns the contents of the title tag in the given HTML, or null if not found. */
private static String extractHtmlTitle(String html) {
  Matcher matcher = HTML_TITLE_TAG_PATTERN.matcher(html);
  return (matcher.find() ? matcher.group(1) : null);
}
 
Example 14
Source File: EppLifecycleDomainTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Test
public void testDomainTransferPollMessage_serverApproved() throws Exception {
  // As the losing registrar, create the domain.
  assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
  createFakesite();
  assertThatLogoutSucceeds();

  // As the winning registrar, request a transfer. Capture the server trid; we'll need it later.
  assertThatLoginSucceeds("TheRegistrar", "password2");
  String response =
      assertThatCommand("domain_transfer_request_1_year.xml")
          .atTime("2001-01-01T00:00:00Z")
          .hasResponse("domain_transfer_response_1_year.xml");
  Matcher matcher = Pattern.compile("<svTRID>(.*)</svTRID>").matcher(response);
  matcher.find();
  String transferRequestTrid = matcher.group(1);
  assertThatLogoutSucceeds();

  // As the losing registrar, read the request poll message, and then ack it.
  assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");
  assertThatCommand("poll.xml")
      .atTime("2001-01-01T00:01:00Z")
      .hasResponse("poll_response_domain_transfer_request.xml");
  assertThatCommand("poll_ack.xml", ImmutableMap.of("ID", "1-C-EXAMPLE-17-23-2001"))
      .atTime("2001-01-01T00:01:00Z")
      .hasResponse("poll_ack_response_empty.xml");

  // Five days in the future, expect a server approval poll message to the loser, and ack it.
  assertThatCommand("poll.xml")
      .atTime("2001-01-06T00:01:00Z")
      .hasResponse("poll_response_domain_transfer_server_approve_loser.xml");
  assertThatCommand("poll_ack.xml", ImmutableMap.of("ID", "1-C-EXAMPLE-17-22-2001"))
      .atTime("2001-01-06T00:01:00Z")
      .hasResponse("poll_ack_response_empty.xml");
  assertThatLogoutSucceeds();

  // Also expect a server approval poll message to the winner, with the transfer request trid.
  assertThatLoginSucceeds("TheRegistrar", "password2");
  assertThatCommand("poll.xml")
      .atTime("2001-01-06T00:02:00Z")
      .hasResponse(
          "poll_response_domain_transfer_server_approve_winner.xml",
          ImmutableMap.of("SERVER_TRID", transferRequestTrid));
  assertThatCommand("poll_ack.xml", ImmutableMap.of("ID", "1-C-EXAMPLE-17-21-2001"))
      .atTime("2001-01-06T00:02:00Z")
      .hasResponse("poll_ack_response_empty.xml");
  assertThatLogoutSucceeds();
}
 
Example 15
Source File: BinlogHelper.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
/**
 * Accepts a string in the format specified by the binary log spec.
 */
@VisibleForTesting
FactoryImpl(BinaryLogSink sink, String configurationString) {
  checkNotNull(sink, "sink");
  BinlogHelper globalLog = null;
  Map<String, BinlogHelper> perServiceLogs = new HashMap<String, BinlogHelper>();
  Map<String, BinlogHelper> perMethodLogs = new HashMap<String, BinlogHelper>();
  Set<String> blacklistedMethods = new HashSet<String>();
  if (configurationString != null && configurationString.length() > 0) {
    for (String configuration : Splitter.on(',').split(configurationString)) {
      Matcher configMatcher = configRe.matcher(configuration);
      if (!configMatcher.matches()) {
        throw new IllegalArgumentException("Illegal log config pattern: " + configuration);
      }
      String methodOrSvc = configMatcher.group(1);
      String binlogOptionStr = configMatcher.group(2);
      if (methodOrSvc.equals("*")) {
        // parse config for "*"
        checkState(
            globalLog == null,
            "Duplicate entry, this is fatal: " + configuration);
        globalLog = createBinaryLog(sink, binlogOptionStr);
        logger.log(Level.INFO, "Global binlog: {0}", binlogOptionStr);
      } else if (isServiceGlob(methodOrSvc)) {
        // parse config for a service, e.g. "service/*"
        String service = MethodDescriptor.extractFullServiceName(methodOrSvc);
        checkState(
            !perServiceLogs.containsKey(service),
            "Duplicate entry, this is fatal: " + configuration);
        perServiceLogs.put(service, createBinaryLog(sink, binlogOptionStr));
        logger.log(
            Level.INFO,
            "Service binlog: service={0} config={1}",
            new Object[] {service, binlogOptionStr});
      } else if (methodOrSvc.startsWith("-")) {
        // parse config for a method, e.g. "-service/method"
        String blacklistedMethod = methodOrSvc.substring(1);
        if (blacklistedMethod.length() == 0) {
          continue;
        }
        checkState(
            !blacklistedMethods.contains(blacklistedMethod),
            "Duplicate entry, this is fatal: " + configuration);
        checkState(
            !perMethodLogs.containsKey(blacklistedMethod),
            "Duplicate entry, this is fatal: " + configuration);
        blacklistedMethods.add(blacklistedMethod);
      } else {
        // parse config for a fully qualified method, e.g "serice/method"
        checkState(
            !perMethodLogs.containsKey(methodOrSvc),
            "Duplicate entry, this is fatal: " + configuration);
        checkState(
            !blacklistedMethods.contains(methodOrSvc),
            "Duplicate entry, this method was blacklisted: " + configuration);
        perMethodLogs.put(methodOrSvc, createBinaryLog(sink, binlogOptionStr));
        logger.log(
            Level.INFO,
            "Method binlog: method={0} config={1}",
            new Object[] {methodOrSvc, binlogOptionStr});
      }
    }
  }
  this.globalLog = globalLog;
  this.perServiceLogs = Collections.unmodifiableMap(perServiceLogs);
  this.perMethodLogs = Collections.unmodifiableMap(perMethodLogs);
  this.blacklistedMethods = Collections.unmodifiableSet(blacklistedMethods);
}
 
Example 16
Source File: GerritChange.java    From copybara with Apache License 2.0 4 votes vote down vote up
/**
 * Given a local repository, a repo url and a reference, it tries to do its best to resolve the
 * reference to a Gerrit Change.
 *
 * <p>Note that if the PatchSet is not found in the ref, it will go to Gerrit to get the latest
 * PatchSet number.
 *
 * @return a Gerrit change if it can be resolved. Null otherwise.
 */
@Nullable
public static GerritChange resolve(
    GitRepository repository, String repoUrl, String ref, GeneralOptions options)
    throws RepoException, ValidationException {
  if (Strings.isNullOrEmpty(ref)) {
    return null;
  }
  Matcher refMatcher = WHOLE_GERRIT_REF.matcher(ref);
  if (refMatcher.matches()) {
    return new GerritChange(
        repository,
        options,
        repoUrl,
        Ints.tryParse(refMatcher.group(1)),
        Ints.tryParse(refMatcher.group(2)),
        ref);
  }
  // A change number like '23423'
  if (CharMatcher.javaDigit().matchesAllOf(ref)) {
    return resolveLatestPatchSet(repository, options, repoUrl, Ints.tryParse(ref));
  }

  Matcher urlMatcher = URL_PATTERN.matcher(ref);
  if (!urlMatcher.matches()) {
    return null;
  }

  if (!ref.startsWith(repoUrl)) {
    // Assume it is our url. We can make this more strict later
    options
        .console()
        .warn(
            String.format(
                "Assuming repository '%s' for looking for review '%s'", repoUrl, ref));
  }
  int change = Ints.tryParse(urlMatcher.group(1));
  Integer patchSet = urlMatcher.group(2) == null ? null : Ints.tryParse(urlMatcher.group(2));
  if (patchSet == null) {
    return resolveLatestPatchSet(repository, options, repoUrl, change);
  }
  Map<Integer, GitRevision> patchSets = getGerritPatchSets(repository, repoUrl, change);
  if (!patchSets.containsKey(patchSet)) {
    throw new CannotResolveRevisionException(
        String.format(
            "Cannot find patch set %d for change %d in %s. Available Patch sets: %s",
            patchSet, change, repoUrl, patchSets.keySet()));
  }
  return new GerritChange(
      repository, options, repoUrl, change, patchSet, patchSets.get(patchSet).contextReference());

}
 
Example 17
Source File: CompareTableB.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
String norm(String s) {
  Matcher matcher = pattern.matcher(s);
  if (!matcher.matches())
    return s;
  return matcher.group(1);
}
 
Example 18
Source File: TodoReplace.java    From copybara with Apache License 2.0 4 votes vote down vote up
private List<String> mapUsers(List<String> users, String rawText, Path path, Console console)
    throws ValidationException {
  Set<String> alreadyAdded = new HashSet<>();
  List<String> result = new ArrayList<>();
  for (String rawUser : users) {
    Matcher matcher = SINGLE_USER_PATTERN.matcher(rawUser);
    // Throw VE if the pattern doesn't match and mode is MAP_OR_FAIL
    if (!matcher.matches()) {
      checkCondition(mode != MAP_OR_FAIL,
          "Unexpected '%s' doesn't match expected format", rawUser);
      console.warnFmt("Skipping '%s' that doesn't match expected format", rawUser);
      continue;
    }
    String prefix = matcher.group(1);
    String originUser = matcher.group(2);
    String suffix = matcher.group(3);
    if (regexIgnorelist != null) {
      if (regexIgnorelist.matcher(originUser).matches()) {
        result.add(prefix + originUser + suffix);
        continue;
      }
    }
    switch (mode) {
      case MAP_OR_FAIL:
        checkCondition(mapping.containsKey(originUser),
            "Cannot find a mapping '%s' in '%s' (%s)", originUser, rawText, path);
        // fall through
      case MAP_OR_IGNORE:
        String destUser = mapping.getOrDefault(originUser, originUser);
        if (alreadyAdded.add(destUser)) {
          result.add(prefix + destUser + suffix);
        }
        break;
      case MAP_OR_DEFAULT:
        destUser = mapping.getOrDefault(originUser, defaultString);
        if (alreadyAdded.add(destUser)) {
          result.add(prefix + destUser + suffix);
        }
        break;
      case SCRUB_NAMES:
        break;
      case USE_DEFAULT:
        if (alreadyAdded.add(defaultString)) {
          result.add(prefix + defaultString + suffix);
        }
        break;
    }
  }
  return result;
}
 
Example 19
Source File: RegexTemplateTokens.java    From copybara with Apache License 2.0 4 votes vote down vote up
private String replaceLine(String line) {
  if (patternsToIgnore != null) {
    for (Pattern patternToIgnore : patternsToIgnore) {
      if (patternToIgnore.matches(line)) {
        return line;
      }
    }
  }

  Matcher matcher = before.matcher(line);
  StringBuilder sb = new StringBuilder(line.length());
  while (matcher.find()) {
    for (Collection<Integer> groupIndexes : repeatedGroups.asMap().values()) {
      // Check that all the references of the repeated group match the same string
      Iterator<Integer> iterator = groupIndexes.iterator();
      String value = matcher.group(iterator.next());
      while (iterator.hasNext()) {
        if (!value.equals(matcher.group(iterator.next()))) {
          return line;
        }
      }
    }
    String replaceTemplate;
    if (callback != null) {
      ImmutableMap.Builder<Integer, String> groupValues =
          ImmutableMap.builder();
      for (int i = 0; i <= matcher.groupCount(); i++) {
        groupValues.put(i, matcher.group(i));
      }
      replaceTemplate = callback.alter(groupValues.build(), afterReplaceTemplate);
    } else {
      replaceTemplate = afterReplaceTemplate;
    }

    matcher.appendReplacement(sb, replaceTemplate);
    if (firstOnly) {
      break;
    }
  }
  matcher.appendTail(sb);
  return sb.toString();
}
 
Example 20
Source File: LatestVersionSelector.java    From copybara with Apache License 2.0 4 votes vote down vote up
@Override
public String selectVersion(
    @Nullable String requestedRef,
    GitRepository repo,
    String url,
    Console console) throws RepoException, ValidationException {
  if (!Strings.isNullOrEmpty(requestedRef)) {
    if (requestedRef.startsWith("force:")) {
      return requestedRef.substring("force:".length());
    }
    console.warnFmt("Ignoring '%s' as git.version_selector is being used.", requestedRef);
  }
  Set<String> refs = repo.lsRemote(url, ImmutableList.of(asGitRefspec())).keySet();

  ImmutableListMultimap<String, Integer> groupIndexes = template.getGroupIndexes();
  List<Object> latest = new ArrayList<>();
  String latestRef = null;
  for (String ref : refs) {
    Matcher matcher = template.getBefore().matcher(ref);
    if (!matcher.matches()) {
      continue;
    }
    List<Object> objs = new ArrayList<>();
    for (Entry<Integer, VersionElementType> groups : groupTypes
        .entrySet()) {
      String var = groups.getValue().varName(groups.getKey());
      String val = matcher.group(Iterables.getLast(groupIndexes.get(var)));
      objs.add(groups.getValue().convert(val));
    }
    if (isAfter(latest, objs)) {
      latest = objs;
      latestRef = ref;
    }
  }

  checkCondition(latestRef != null,
      "version_selector didn't match any version for '%s'", template.getBefore().pattern());

  // It is rare that a branch and a tag has the same name. The reason for this is that
  // destinations expect that the context_reference is a non-full reference. Also it is
  // more readable when we use it in transformations.
  if (latestRef.startsWith("refs/heads/")) {
    return latestRef.substring("refs/heads/".length());
  }
  if (latestRef.startsWith("refs/tags/")) {
    return latestRef.substring("refs/tags/".length());
  }
  return latestRef;
}