com.google.re2j.Matcher Java Examples

The following examples show how to use com.google.re2j.Matcher. 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: NameserversParameter.java    From nomulus with 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 #2
Source File: IgraPor.java    From netcdf-java with 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 #3
Source File: IgraPor.java    From netcdf-java with 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 #4
Source File: Ghcnm2.java    From netcdf-java with 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 #5
Source File: Ghcnm2.java    From netcdf-java with 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 #6
Source File: IgraPor.java    From netcdf-java with 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 #7
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 #8
Source File: Ghcnm2.java    From netcdf-java with 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 File: DateFromString.java    From netcdf-java with 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 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 #11
Source File: Re2JRegexp.java    From presto with 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 #12
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 #13
Source File: FilterReplace.java    From copybara with 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 #14
Source File: GerritDestination.java    From copybara with 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 #15
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 #16
Source File: RouteMethod.java    From mangooio with 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 #17
Source File: RdeUtil.java    From nomulus with 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 #18
Source File: ScannerPqact.java    From netcdf-java with 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 #19
Source File: GempakParameterTable.java    From netcdf-java with 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 #20
Source File: Http.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private String replaceStatusLineToNonProxyStyte(String status_line) throws Exception
{
	String result = status_line;
	Pattern pattern = Pattern.compile("http://[^/]+");
	Matcher matcher = pattern.matcher(status_line);
	if (matcher.find()) {
		result = matcher.replaceAll("");
	}
	return result;
}
 
Example #21
Source File: JavaAnalyzer.java    From coderadar with MIT License 5 votes vote down vote up
public String getPackageName(byte[] byteFileContent) {
  if (byteFileContent != null) {
    String fileContent = clearFileContent(new String(byteFileContent));
    Matcher packageMatcher = cache.getPattern(PACKAGE_PATTERN).matcher(fileContent);
    if (packageMatcher.find()) {
      Matcher nameMatcher = cache.getPattern(NAME_PATTERN).matcher(packageMatcher.group());
      if (nameMatcher.find()) {
        return nameMatcher.group().substring(1);
      }
    }
  }
  return "";
}
 
Example #22
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 #23
Source File: GetSchemaTreeCommandTest.java    From nomulus with 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 #24
Source File: Re2JRegexp.java    From presto with Apache License 2.0 5 votes vote down vote up
public Block split(Slice source)
{
    Matcher matcher = re2jPattern.matcher(source);
    BlockBuilder blockBuilder = VARCHAR.createBlockBuilder(null, 32);

    int lastEnd = 0;
    while (matcher.find()) {
        Slice slice = source.slice(lastEnd, matcher.start() - lastEnd);
        lastEnd = matcher.end();
        VARCHAR.writeSlice(blockBuilder, slice);
    }

    VARCHAR.writeSlice(blockBuilder, source.slice(lastEnd, source.length() - lastEnd));
    return blockBuilder.build();
}
 
Example #25
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 #26
Source File: Modification.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
private byte[] replaceRegex(byte[] data, Packet packet) {
	Pattern pattern = Pattern.compile(this.pattern, Pattern.MULTILINE);
	Matcher matcher = pattern.matcher(new String(data));
	String result = new String(data);
	while (matcher.find()) {
		result = matcher.replaceAll(this.replaced);
		packet.setModified();
	}
	return result.getBytes();
}
 
Example #27
Source File: CamelCase.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
static public String toCamelCase(String s) {
	Pattern pattern = Pattern.compile("([a-zA-Z][a-zA-Z0-9]*)");
	Matcher matcher = pattern.matcher(s);
	StringBuffer sb = new StringBuffer();
	while (matcher.find()) {
		matcher.appendReplacement(sb, toProperCase(matcher.group()));
	}
	matcher.appendTail(sb);
	return sb.toString();
}
 
Example #28
Source File: StringUtils.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
/**
 * バイナリを壊さないでパターンマッチングをする人です。疑似的に実現しているので、ascii以外は0x01にマッピングしてから比較しているのでマルチバイトの検索はできません
 *
 * @param input
 * @param regex
 * @param replace
 * @return
 */
public static byte[] pseudoBinaryPatternReplace(byte[] input, String regex, String replace) {
	byte[] input2 = input.clone();
	for(int i=0; i<input2.length; ++i) {
		if(input2[i] < 0x00) {
			input2[i] = 0x01;
		}
	}
	String pseudoString = new String(input2);
	Pattern pattern = Pattern.compile(regex);
	Matcher matcher = pattern.matcher(pseudoString);
	ByteArrayOutputStream result = new ByteArrayOutputStream();
	if(matcher.find()) {
		String matched = matcher.group(0);
		int from = pseudoString.indexOf(matched);
		//System.err.println("Match! : " + pseudoString.length() + " : " + from + " : " + regex + " : " + pseudoString);
		byte[] tmp_result = new byte[matched.length()];
		for(int i=0; i<matched.length(); ++i) {
			tmp_result[i] = input[from+i];
		}
		result.write(input,0,from);
		//System.err.println(result);
		result.write(replace.getBytes(),0,replace.getBytes().length);
		//System.err.println(result);
		result.write(input,from+matched.length(),input.length-(from+matched.length()));
		//System.err.println(result);
	}
	return result.toByteArray();
}
 
Example #29
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 #30
Source File: Http.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
private void analyzeStatusLine(String status_line) throws Exception
{
	Pattern pattern = Pattern.compile("^([^ ]+)");
	Matcher matcher = pattern.matcher(status_line);
	if (matcher.find()) {
		if (matcher.group(1).trim().startsWith("HTTP")) {
			analyzeResponseStatusLine(status_line);
		} else {
			flag_request = true;
			analyzeRequestStatusLine(status_line);
		}
	}
}