Java Code Examples for com.google.re2j.Matcher

The following examples show how to use com.google.re2j.Matcher. These examples are extracted from open source projects. 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 Project: netcdf-java   Author: Unidata   File: GempakParameterTable.java    License: 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 #2
Source Project: netcdf-java   Author: Unidata   File: GempakParameterTable.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the input stream to the given resource
 *
 * @param resourceName The resource name. May be a file, url,
 *        java resource, etc.
 * @return The input stream to the resource
 */
private InputStream getInputStream(String resourceName) throws IOException {

  // Try class loader to get resource
  ClassLoader cl = GempakParameterTable.class.getClassLoader();
  InputStream s = cl.getResourceAsStream(resourceName);
  if (s != null) {
    return s;
  }

  // Try the file system
  File f = new File(resourceName);
  if (f.exists()) {
    s = new FileInputStream(f);
  }
  if (s != null) {
    return s;
  }

  // Try it as a url
  Matcher m = Pattern.compile(" ").matcher(resourceName);
  String encodedUrl = m.replaceAll("%20");
  URL dataUrl = new URL(encodedUrl);
  URLConnection connection = dataUrl.openConnection();
  return connection.getInputStream();
}
 
Example #3
Source Project: netcdf-java   Author: Unidata   File: IgraPor.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public StructureData next() throws IOException {
  Matcher matcher;
  while (true) {
    String line = vinfo.rafile.readLine();
    if (line == null)
      return null;
    if (line.startsWith("#"))
      continue;
    if (line.trim().isEmpty())
      continue;
    matcher = vinfo.p.matcher(line);
    if (matcher.matches()) {
      String stnid = matcher.group(stn_fldno).trim();
      if (stnid.equals(stationId))
        break;
    }
  }
  recno++;
  return new StationData(vinfo.sm, matcher);
}
 
Example #4
Source Project: netcdf-java   Author: Unidata   File: IgraPor.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private StructureData reallyNext() throws IOException {
  Matcher matcher;
  while (true) {
    String line = vinfo.rafile.readLine();
    if (line == null)
      return null;
    if (line.startsWith("#"))
      continue;
    if (line.trim().isEmpty())
      continue;
    matcher = vinfo.p.matcher(line);
    if (matcher.matches())
      break;
    logger.error("FAIL at line {}", line);
  }
  recno++;
  return new StationData(vinfo.sm, matcher);
}
 
Example #5
Source Project: netcdf-java   Author: Unidata   File: IgraPor.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public StructureData next() throws IOException {
  Matcher matcher;
  String line;
  while (true) {
    line = timeSeriesRaf.readLine();
    if (line == null)
      return null; // only on EOF
    if (line.trim().isEmpty())
      continue;
    matcher = seriesVinfo.p.matcher(line);
    if (matcher.matches())
      break;
    logger.error("FAIL TimeSeriesIter at line {}", line);
  }
  countRead++;
  return new TimeSeriesData(matcher);
}
 
Example #6
Source Project: netcdf-java   Author: Unidata   File: Ghcnm2.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean isValidFile(RandomAccessFile raf, Pattern p) throws IOException {
  raf.seek(0);
  String line;
  while (true) {
    line = raf.readLine();
    if (line == null)
      break;
    if (line.startsWith("#"))
      continue;
    if (line.trim().isEmpty())
      continue;
    Matcher matcher = p.matcher(line);
    return matcher.matches();
  }
  return false;
}
 
Example #7
Source Project: netcdf-java   Author: Unidata   File: Ghcnm2.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private StructureData reallyNext() throws IOException {
  Matcher matcher;
  while (true) {
    String line = vinfo.rafile.readLine();
    if (line == null)
      return null;
    if (line.startsWith("#"))
      continue;
    if (line.trim().isEmpty())
      continue;
    matcher = vinfo.p.matcher(line);
    if (matcher.matches())
      break;
    logger.warn("FAIL on line {}", line);
  }
  bytesRead = vinfo.rafile.getFilePointer();
  recno++;
  return new StructureDataRegexpGhcnm(vinfo.sm, matcher);
}
 
Example #8
Source Project: netcdf-java   Author: Unidata   File: Ghcnm2.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public StructureData next() throws IOException {
  Matcher matcher;
  String line;
  while (true) {
    line = dataRaf.readLine();
    if (line == null)
      return null;
    if (line.startsWith("#"))
      continue;
    if (line.trim().isEmpty())
      continue;
    matcher = dataPattern.matcher(line);
    if (matcher.matches())
      break;
  }
  countRead++;
  return new StructureDataRegexp(sm, matcher);
}
 
Example #9
Source Project: netcdf-java   Author: Unidata   File: DateFromString.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * The same as getDateUsingRegExp() except the date format string to be used
 * must be specified.
 *
 * @param dateString the String to be parsed
 * @param matchPattern the regular expression String on which to match.
 * @param substitutionPattern the String to use in the capture group replacement.
 * @param dateFormatString the date format string to use in the parsing of the date string.
 * @return the calculated Date
 */
public static Date getDateUsingRegExpAndDateFormat(String dateString, String matchPattern, String substitutionPattern,
    String dateFormatString) {
  // Match the given date string against the regular expression.
  Pattern pattern = Pattern.compile(matchPattern);
  Matcher matcher = pattern.matcher(dateString);
  if (!matcher.matches()) {
    return null;
  }

  // Build date string to use with date format string by
  // substituting the capture groups into the substitution pattern.
  StringBuffer dateStringFormatted = new StringBuffer();
  matcher.appendReplacement(dateStringFormatted, substitutionPattern);
  if (dateStringFormatted.length() == 0) {
    return null;
  }

  return getDateUsingCompleteDateFormat(dateStringFormatted.toString(), dateFormatString);
}
 
Example #10
Source Project: netcdf-java   Author: Unidata   File: TestGhcnm.java    License: 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 #11
Source Project: netcdf-java   Author: Unidata   File: ScannerPqact.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
boolean match(String header, Message m) {
  Matcher matcher = pattern.matcher(header);
  if (!matcher.matches())
    return false;

  if (first == null) {
    first = m;
  } else if (m.hashCode() != first.hashCode()) {
    System.out.println(" DDS doesnt match pqact= " + pats);
    first.dumpHeader(out);
    m.dumpHeader(out);
    System.out.println();
    badmatch++;
    return false;
  }
  count++;
  return true;
}
 
Example #12
Source Project: presto   Author: prestosql   File: Re2JRegexp.java    License: Apache License 2.0 6 votes vote down vote up
public Block extractAll(Slice source, long groupIndex)
{
    Matcher matcher = re2jPattern.matcher(source);
    int group = toIntExact(groupIndex);
    validateGroup(group, matcher.groupCount());

    BlockBuilder blockBuilder = VARCHAR.createBlockBuilder(null, 32);
    while (true) {
        if (!matcher.find()) {
            break;
        }

        Slice searchedGroup = matcher.group(group);
        if (searchedGroup == null) {
            blockBuilder.appendNull();
            continue;
        }
        VARCHAR.writeSlice(blockBuilder, searchedGroup);
    }
    return blockBuilder.build();
}
 
Example #13
Source Project: PacketProxy   Author: DeNA   File: ProxyHttpTransparent.java    License: 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 #14
Source Project: copybara   Author: google   File: FilterReplace.java    License: Apache License 2.0 6 votes vote down vote up
private String replaceString(String originalContent) {
  Pattern pattern = Pattern.compile(before.pattern());
  Matcher matcher = pattern.matcher(originalContent);

  boolean anyReplace = false;
  StringBuilder result = new StringBuilder(originalContent.length());
  while (matcher.find()) {
    String val = matcher.group(FilterReplace.this.group);
    String res = mapping.apply(val);
    anyReplace |= !val.equals(res);
    if (group == 0) {
      matcher.appendReplacement(result, Matcher.quoteReplacement(res));
    } else {
      String prefix = originalContent.substring(matcher.start(), matcher.start(group));
      String suffix = originalContent.substring(matcher.end(group), matcher.end());
      matcher.appendReplacement(result, Matcher.quoteReplacement((prefix + res + suffix)));
    }
  }

  if (!anyReplace) {
    return originalContent;
  }

  matcher.appendTail(result);
  return result.toString();
}
 
Example #15
Source Project: copybara   Author: google   File: GerritDestination.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private Matcher tryFindGerritUrl(List<String> lines) {
  boolean successFound = false;
  for (String line : lines) {
    if ((line.contains("SUCCESS"))) {
      successFound = true;
    }
    if (successFound) {
      // Usually next line is empty, but let's try best effort to find the URL after "SUCCESS"
      Matcher urlMatcher = GERRIT_URL_LINE.matcher(line);
      if (urlMatcher.matches()) {
        return urlMatcher;
      }
    }
  }
  return null;
}
 
Example #16
Source Project: nomulus   Author: google   File: SqlTemplate.java    License: 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 #17
Source Project: mangooio   Author: svenkubiak   File: RouteMethod.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TemplateModel exec(List arguments) throws TemplateModelException {
    String url;
    if (arguments.size() >= MIN_ARGUMENTS) {
        String controller = ((SimpleScalar) arguments.get(0)).getAsString();
        RequestRoute requestRoute = Router.getReverseRoute(controller);
        
        if (requestRoute != null) {
            url = requestRoute.getUrl();
            Matcher matcher = PARAMETER_PATTERN.matcher(url);
            int i = 1;
            while (matcher.find()) {
                String argument = ((SimpleScalar) arguments.get(i)).getAsString();
                url = StringUtils.replace(url, "{" + matcher.group(1) + "}", argument);
                i++;
            }
        } else {
            throw new TemplateModelException("Reverse route for " + controller + " could not be found!");
        }
    } else {
        throw new TemplateModelException("Missing at least one argument (ControllerClass:ControllerMethod) for reverse routing!");
    }

    return new SimpleScalar(url);
}
 
Example #18
Source Project: nomulus   Author: google   File: RdeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Look at some bytes from {@code xmlInput} to ensure it appears to be a FULL XML deposit and
 * then use a regular expression to extract the watermark timestamp which is returned.
 */
public static DateTime peekWatermark(BufferedInputStream xmlInput)
    throws IOException, XmlException {
  xmlInput.mark(PEEK_SIZE);
  byte[] peek = new byte[PEEK_SIZE];
  if (xmlInput.read(peek) != PEEK_SIZE) {
    throw new IOException(String.format("Failed to peek %,d bytes on input file", PEEK_SIZE));
  }
  xmlInput.reset();
  String peekStr = new String(peek, UTF_8);
  if (!peekStr.contains("urn:ietf:params:xml:ns:rde-1.0")) {
    throw new XmlException(String.format(
        "Does not appear to be an XML RDE deposit\n%s", dumpHex(peek)));
  }
  if (!peekStr.contains("type=\"FULL\"")) {
    throw new XmlException("Only FULL XML RDE deposits suppported at this time");
  }
  Matcher watermarkMatcher = WATERMARK_PATTERN.matcher(peekStr);
  if (!watermarkMatcher.find()) {
    throw new XmlException("Could not find RDE watermark in XML");
  }
  return DATETIME_FORMATTER.parseDateTime(watermarkMatcher.group(1));
}
 
Example #19
Source Project: nomulus   Author: google   File: NameserversParameter.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Stream<String> splitNameservers(String ns) {
  Matcher matcher = FORMAT_BRACKETS.matcher(ns);
  if (!matcher.matches()) {
    checkArgument(
        !ns.contains("[") && !ns.contains("]"), "Could not parse square brackets in %s", ns);
    return ImmutableList.of(ns).stream();
  }

  ImmutableList.Builder<String> nameservers = new ImmutableList.Builder<>();
  int start = parseInt(matcher.group(2));
  int end = parseInt(matcher.group(3));
  checkArgument(start <= end, "Number range [%s-%s] is invalid", start, end);
  for (int i = start; i <= end; i++) {
    nameservers.add(String.format("%s%d%s", matcher.group(1), i, matcher.group(4)));
  }
  return nameservers.build().stream();
}
 
Example #20
Source Project: jinjava   Author: HubSpot   File: RegexReplaceFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  if (args.length < 2) {
    throw new TemplateSyntaxException(
      interpreter,
      getName(),
      "requires 2 arguments (regex string, replacement string)"
    );
  }

  if (var == null) {
    return null;
  }

  if (var instanceof String) {
    String s = (String) var;
    String toReplace = args[0];
    String replaceWith = args[1];

    try {
      Pattern p = Pattern.compile(toReplace);
      Matcher matcher = p.matcher(s);

      return matcher.replaceAll(replaceWith);
    } catch (PatternSyntaxException e) {
      throw new InvalidArgumentException(
        interpreter,
        this,
        InvalidReason.REGEX,
        0,
        toReplace
      );
    }
  } else {
    throw new InvalidInputException(interpreter, this, InvalidReason.STRING);
  }
}
 
Example #21
Source Project: netcdf-java   Author: Unidata   File: IgraPor.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean isValidFile(RandomAccessFile raf, Pattern p) throws IOException {
  raf.seek(0);
  String line;
  while (true) {
    line = raf.readLine();
    if (line == null)
      break;
    if (line.trim().isEmpty())
      continue;
    Matcher matcher = p.matcher(line);
    return matcher.matches();
  }
  return false;
}
 
Example #22
Source Project: nomulus   Author: google   File: GetSchemaTreeCommandTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAllClassesPrintedExactlyOnce() throws Exception {
  runCommand();
  String stdout = getStdoutAsString();
  for (Class<?> clazz : EntityClasses.ALL_CLASSES) {
    String printableName = GetSchemaTreeCommand.getPrintableName(clazz);
    int count = 0;
    Matcher matcher = Pattern.compile("(^|\\s)" + printableName + "\\s").matcher(stdout);
    while (matcher.find()) {
      count++;
    }
    assertWithMessage(printableName + " occurences").that(count).isEqualTo(1);
  }
}
 
Example #23
Source Project: netcdf-java   Author: Unidata   File: IgraPor.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public StructureData next() {
  if (!hasNext())
    return null;
  Matcher matcher = profileVinfo.p.matcher(lines.get(countRead));
  StructureData sd;
  if (matcher.matches())
    sd = new StructureDataRegexp(profileVinfo.sm, matcher);
  else
    throw new IllegalStateException("line = " + lines.get(countRead) + "pattern = " + profileVinfo.p);
  countRead++;
  return sd;
}
 
Example #24
Source Project: netcdf-java   Author: Unidata   File: WildcardMatchOnPath.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public boolean accept(MFile file) {
  String p = file.getPath();
  Matcher matcher = this.pattern.matcher(p);
  if (debug)
    System.out.printf(" WildcardMatchOnPath regexp %s on %s match=%s%n", pattern, file.getPath(), matcher.matches());
  return matcher.matches();
}
 
Example #25
Source Project: netcdf-java   Author: Unidata   File: StreamFilter.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean accept(Path entry) {

  String matchOn = nameOnly ? entry.getName(entry.getNameCount() - 1).toString()
      : StringUtil2.replace(entry.toString(), "\\", "/");
  Matcher matcher = this.pattern.matcher(matchOn);
  return matcher.matches();
}
 
Example #26
Source Project: netcdf-java   Author: Unidata   File: CalendarDateUnit.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private CalendarDateUnit(Calendar calt, String dateUnitString) {

    dateUnitString = dateUnitString.trim();
    // dateUnitString = dateUnitString.replaceAll("\\s+", " "); LOOK think about should we allow this ??
    dateUnitString = dateUnitString.toLowerCase();

    isCalendarField = dateUnitString.startsWith(byCalendarString);
    if (isCalendarField) {
      dateUnitString = dateUnitString.substring(byCalendarString.length()).trim();
    }

    Matcher m = udunitPattern.matcher(dateUnitString);
    if (!m.matches()) {
      throw new IllegalArgumentException(dateUnitString + " does not match " + udunitPatternString);
    }

    String unitString = m.group(1);
    period = CalendarPeriod.of(unitString);
    periodField = CalendarPeriod.fromUnitString(unitString);

    int pos = dateUnitString.indexOf("since");
    String iso = dateUnitString.substring(pos + 5);
    baseDate = CalendarDateFormatter.isoStringToCalendarDate(calt, iso);

    // calendar might change !!
    calt = baseDate.getCalendar();
    this.cal = calt;
  }
 
Example #27
Source Project: netcdf-java   Author: Unidata   File: TestRegexp.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void testMatch(String ps, String match, boolean expect, String[] groups) {
  Pattern pattern = Pattern.compile(ps);
  Matcher matcher = pattern.matcher(match);

  assertEquals("Match " + ps + " against " + match, expect, matcher.matches());

  if (groups != null) {
    for (int i = 1; i <= matcher.groupCount(); ++i)
      assertEquals("Wrong group " + i, groups[i - 1], matcher.group(i));
  }
}
 
Example #28
Source Project: netcdf-java   Author: Unidata   File: Message.java    License: 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 #29
Source Project: netcdf-java   Author: Unidata   File: Scanner.java    License: 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 #30
Source Project: netcdf-java   Author: Unidata   File: Scanner.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static void extractAllWithHeader(String filein, Pattern p, WritableByteChannel wbc) throws IOException {
  System.out.println("extract " + filein);
  try (RandomAccessFile raf = new RandomAccessFile(filein, "r")) {
    MessageScanner scan = new MessageScanner(raf);
    while (scan.hasNext()) {
      Message m = scan.next();
      Matcher matcher = p.matcher(m.getHeader());
      if (matcher.matches()) {
        scan.writeCurrentMessage(wbc);
        System.out.println(" found match " + m.getHeader());
      }
    }
  }
}