Java Code Examples for com.google.re2j.Pattern#matcher()

The following examples show how to use com.google.re2j.Pattern#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: 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 2
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 3
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 4
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 5
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 6
Source File: IgraPor.java    From netcdf-java with 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 7
Source File: TodoReplace.java    From copybara with Apache License 2.0 5 votes vote down vote up
private Set<FileState> run(Iterable<FileState> files, Console console)
    throws IOException, ValidationException {
  Set<FileState> modifiedFiles = new HashSet<>();
  // TODO(malcon): Remove reconstructing pattern once RE2J doesn't synchronize on matching.
  Pattern batchPattern = Pattern.compile(pattern.pattern(), pattern.flags());
  for (FileState file : files) {
    if (Files.isSymbolicLink(file.getPath())) {
      continue;
    }
    String content = new String(Files.readAllBytes(file.getPath()), UTF_8);
    Matcher matcher = batchPattern.matcher(content);
    StringBuffer sb = new StringBuffer();
    boolean modified = false;
    while (matcher.find()) {
      if (matcher.group(2).trim().isEmpty()){
        matcher.appendReplacement(sb, matcher.group(0));
        continue;
      }
      List<String> users = Splitter.on(",").splitToList(matcher.group(2));
      List<String> mappedUsers = mapUsers(users, matcher.group(0), file.getPath(), console);
      modified |= !users.equals(mappedUsers);
      String result = matcher.group(1);
      if (!mappedUsers.isEmpty()) {
        result += "(" + Joiner.on(",").join(mappedUsers) + ")";
      }
      matcher.appendReplacement(sb, Matcher.quoteReplacement(result));
    }
    matcher.appendTail(sb);

    if (modified) {
      modifiedFiles.add(file);
      Files.write(file.getPath(), sb.toString().getBytes(UTF_8));
    }
  }
  return modifiedFiles;
}
 
Example 8
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 9
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 10
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 11
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);
		}
	}
}
 
Example 12
Source File: Http.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
private void analyzeResponseStatusLine(String status_line) throws Exception
{
	Pattern pattern = Pattern.compile("[^ ]+ +([^ ]+) +([a-z0-9A-Z ]+)$");
	Matcher matcher = pattern.matcher(status_line);
	if (matcher.find()) {
		this.statusCode = matcher.group(1).trim();
		//			if (matcher.group(2).trim().equals("Connection established")) {
		//				//flag_httpsは使ってない
		//				flag_https = true;
		//			}
	}
}
 
Example 13
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 14
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 15
Source File: UnitTestCommon.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String modify(String text) {
  StringBuilder result = new StringBuilder(text);
  for (Pattern p : patterns) {
    for (;;) {
      Matcher m = p.matcher(result.toString());
      if (!m.matches())
        break;
      int pos0 = m.start();
      int pos1 = m.end();
      result.delete(pos0, pos1);
    }
  }
  return result.toString();
}
 
Example 16
Source File: TestServletLogParser.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void show(String s, Pattern p) {
  System.out.println("==============================");
  Matcher m = p.matcher(s);
  System.out.printf(" match against %s = %s %n", m, m.matches());
  if (!m.matches())
    return;
  for (int i = 1; i <= m.groupCount(); i++)
    System.out.println(" " + i + " " + m.group(i));

}
 
Example 17
Source File: Scanner.java    From netcdf-java with 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());
      }
    }
  }
}
 
Example 18
Source File: TestRegexp.java    From netcdf-java with 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 19
Source File: InterceptOption.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
private boolean matchRegex(byte[] data) {
	Pattern pattern = Pattern.compile(this.pattern, Pattern.MULTILINE);
	Matcher matcher = pattern.matcher(new String(data));
	return matcher.find();
}
 
Example 20
Source File: TestRegexp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void testOne(String ps, String match, boolean expect) {
  Pattern pattern = Pattern.compile(ps);
  Matcher matcher = pattern.matcher(match);
  assertEquals("match " + ps + " against: " + match, expect, matcher.matches());
}