下面列出了java.util.regex.Matcher#find ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String stripUIRefsFromInspectionDescription(String description) {
final int descriptionEnd = description.indexOf("<!-- tooltip end -->");
if (descriptionEnd < 0) {
final Pattern pattern = Pattern.compile(".*Use.*(the (panel|checkbox|checkboxes|field|button|controls).*below).*", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(description);
int startFindIdx = 0;
while (matcher.find(startFindIdx)) {
final int end = matcher.end(1);
startFindIdx = end;
description = description.substring(0, matcher.start(1)) + " inspection settings " + description.substring(end);
}
} else {
description = description.substring(0, descriptionEnd);
}
return description;
}
private static String removeByRegex(String inputString, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
StringBuilder sb = new StringBuilder(inputString);
Set<String> wrapped = new LinkedHashSet<>();
while (matcher.find()) {
wrapped.add(matcher.group());
}
for (String str : wrapped) {
int from = -1;
int to = -1;
while ((from = sb.indexOf(str)) != -1) {
to = from + str.length();
sb.replace(from, to, "");
}
}
return sb.toString();
}
public static void addEventLogEntry(Event event, Location<World> location, Object source, Object target, Subject permissionSubject, String permission, String trust, Tristate result) {
if (GriefPreventionPlugin.debugActive) {
String sourceId = getPermissionIdentifier(source, true);
String targetPermission = permission;
String targetId = getPermissionIdentifier(target);
if (!targetId.isEmpty()) {
// move target meta to end of permission
Matcher m = PATTERN_META.matcher(targetId);
String targetMeta = "";
if (!permission.contains("command-execute")) {
if (m.find()) {
targetMeta = m.group(0);
targetId = StringUtils.replace(targetId, targetMeta, "");
}
}
targetPermission += "." + targetId + targetMeta;
}
if (permissionSubject == null) {
permissionSubject = GriefPreventionPlugin.GLOBAL_SUBJECT;
}
GriefPreventionPlugin.addEventLogEntry(event, location, sourceId, targetId, permissionSubject, targetPermission, trust, result);
}
}
private static String getAaptResult(String sdkPath, String apkPath, final Pattern pattern) {
try {
final File apkFile = new File(apkPath);
final ByteArrayOutputStream aaptOutput = new ByteArrayOutputStream();
final String command = getAaptDumpBadgingCommand(sdkPath, apkFile.getName());
Process process = Runtime.getRuntime().exec(command, null, apkFile.getParentFile());
InputStream inputStream = process.getInputStream();
for (int last = inputStream.read(); last != -1; last = inputStream.read()) {
aaptOutput.write(last);
}
String packageId = "";
final String aaptResult = aaptOutput.toString();
if (aaptResult.length() > 0) {
final Matcher matcher = pattern.matcher(aaptResult);
if (matcher.find()) {
packageId = matcher.group(1);
}
}
return packageId;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<EnumMetaDada> string2EnumMetaData(String data) {
if (data == null || data.trim().length() == 0)
return new ArrayList();
//enumAlias(enumKey,enumDesc),enumAlias(enumDesc)
List<EnumMetaDada> list = new ArrayList();
Pattern p = Pattern.compile("\\w+\\(.*?\\)");
Matcher m = p.matcher(data);
while (m.find()) {
String str = m.group();
Matcher three_m = three.matcher(str);
if (three_m.find()) {
list.add(new EnumMetaDada(three_m.group(1), three_m.group(2), three_m.group(3)));
continue;
}
Matcher two_m = two.matcher(str);
if (two_m.find()) {
list.add(new EnumMetaDada(two_m.group(1), two_m.group(1), two_m.group(2)));
continue;
}
throw new IllegalArgumentException("error enumString format:" + data + " expected format:F(1,Female);M(0,Male) or F(Female);M(Male)");
}
return list;
}
public static SQLQuery replaceNamedParameters( String query, Map<String, Object> namedParameters )
{ // replace #{namedVar} in query with ? and appends corresponding parameter from map namedParameters
Pattern p = Pattern.compile("#\\{\\s*([^\\s\\}]+)\\s*\\}");
SQLQuery qry = new SQLQuery();
Matcher m = p.matcher( query );
while( m.find() )
{ String nParam = m.group(1);
if( !namedParameters.containsKey(nParam) )
throw new IllegalArgumentException("sql: named Parameter ["+ nParam +"] missing");
qry.addParameter( namedParameters.get(nParam) );
}
qry.append( m.replaceAll("?") );
return qry;
}
/**
* 匹配 str 中符合表达式 p的第一个
*
* @param p
* @param str
* @return
*/
public static String match(String p, String str) {
Pattern pattern = Pattern.compile(p);
Matcher m = pattern.matcher(str);
if (m.find()) {
return m.group(1);
}
return null;
}
public String encodeUrlsAsHtml(String text) {
// MOVED FROM Web
Pattern p = Pattern.compile("(?<!href=['\"]{1})(((https?|s?ftp|ftps|file|smb|afp|nfs|(x-)?man|gopher|txmt)://|mailto:)[-:;@a-zA-Z0-9_.,~%+/?=&#]+(?<![.,?:]))");
Matcher m = p.matcher(text);
StringBuffer buf = new StringBuffer();
while(m.find()) {
String matchedUrl = m.group();
m.appendReplacement(buf, "<a href=\"" + unEscapeHtml(matchedUrl) + "\">$1</a>");
}
m.appendTail(buf);
return buf.toString();
}
public static String[] splitCommandWithoutRemovingQuotes(String command) {
List<String> list = new ArrayList<>();
Matcher m = Pattern.compile("(\\\\\"\\\\\"|[^\\\\\"]\\S*|\\\\\".+?\\\\\")\\s*").matcher(command);
while (m.find()) {
list.add(m.group(1).replaceAll("\\\\\"", "\""));
}
return list.toArray(new String[list.size()]);
}
private void replaceParameterBindings(List<AbstractAggregateQueryProvider.ParameterBinding> bindings, Matcher valueMatcher, String prefix,
boolean quoted) {
while (valueMatcher.find()) {
int paramIndex = Integer.parseInt(valueMatcher.group(PARAMETER_INDEX_GROUP));
bindings.add(new AbstractAggregateQueryProvider.ParameterBinding(paramIndex, quoted, prefix));
}
}
/**
* Returns the default JTReg arguments for a jvm running a test without
* options that matches regular expressions in {@code filters}.
* This is the combination of JTReg arguments test.vm.opts and test.java.opts.
* @param filters Regular expressions used to filter out options.
* @return An array of options, or an empty array if no options.
*/
public static String[] getFilteredTestJavaOpts(String... filters) {
String options[] = getTestJavaOpts();
if (filters.length == 0) {
return options;
}
List<String> filteredOptions = new ArrayList<String>(options.length);
Pattern patterns[] = new Pattern[filters.length];
for (int i = 0; i < filters.length; i++) {
patterns[i] = Pattern.compile(filters[i]);
}
for (String option : options) {
boolean matched = false;
for (int i = 0; i < patterns.length && !matched; i++) {
Matcher matcher = patterns[i].matcher(option);
matched = matcher.find();
}
if (!matched) {
filteredOptions.add(option);
}
}
return filteredOptions.toArray(new String[filteredOptions.size()]);
}
private static String generateMessage(String message, Object... args) {
int index = 0;
Matcher matcher = REPLACE_PATTERN.matcher(message);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, Matcher.quoteReplacement(String.valueOf(args[index++])));
}
matcher.appendTail(sb);
return sb.toString();
}
protected boolean processLike(Object column_value, Object v) {
if (!(v == null || v instanceof String)) {// TODO shenxun
// 丢异常才对,但老实现丢异常会出现无法关闭cursor的问题。所以返回false.
return false;
}
String colValString = "";
if (column_value != null) {
colValString = String.valueOf(column_value);
}
String tar = (String) v;
if (tarCache == null || !tarCache.equals(tar)) {
if (pattern != null) {
throw new IllegalArgumentException("should not be here");
}
tarCache = tar;
// trim and remove %%
tar = TStringUtil.trim(tar);
tar = TStringUtil.replace(tar, "\\_", "[uANDOR]");
tar = TStringUtil.replace(tar, "\\%", "[pANDOR]");
tar = TStringUtil.replace(tar, "%", ".*");
tar = TStringUtil.replace(tar, "_", ".");
tar = TStringUtil.replace(tar, "[uANDOR]", "\\_");
tar = TStringUtil.replace(tar, "[pANDOR]", "\\%");
// case insensitive
tar = "(?i)" + tar;
tar = "^" + tar;
tar = tar + "$";
pattern = Pattern.compile(tar);
}
Matcher matcher = pattern.matcher(colValString);
return matcher.find();
}
public static Match extract(Matcher matcher, String matchee, IndexType type, int index) {
matcher.reset(matchee);
switch (type) {
case INDEX:
case INDEX_BACKWARDS:
List<Match> matches = new ArrayList<Match>();
while (matcher.find()) {
matches.add(PatternMatchUtils.match(matcher));
}
int length = matches.size();
int i = (type == INDEX_BACKWARDS) ? length - 1 - index : index;
if (i < matches.size() && i >= 0) {
return matches.get(i);
}
break;
case CAPTURE_GROUP:
if (matcher.matches()) {
if (index >= 0 && index < matcher.groupCount()) {
return PatternMatchUtils.groupMatch(matcher, index);
}
}
break;
default:
throw new UnsupportedOperationException(type.name());
}
return null;
}
public boolean parseLine(String line){
Matcher m=pattern.matcher(line);
if(!m.find()) return false;
//get dictionary data and fix them up
String[] targets=m.group(2).split("/");
for(int i=0;i<targets.length;i++){
dict.add(m.group(1).trim().toLowerCase()
,targets[i].trim().toLowerCase());
}
return true;
}
/**
* Encode a string for use in the path of a URL; uses URLEncoder.encode,
* (which encodes a string for use in the query portion of a URL), then
* applies some postfilters to fix things up per the RFC. Can optionally
* handle strings which are meant to encode a path (ie include '/'es
* which should NOT be escaped).
*
* @param value the value to encode
* @param path true if the value is intended to represent a path
* @return the encoded value
*/
public static String urlEncode(final String value, final boolean path) {
if (value == null) {
return "";
}
try {
String encoded = URLEncoder.encode(value, DEFAULT_ENCODING);
Matcher matcher = ENCODED_CHARACTERS_PATTERN.matcher(encoded);
StringBuffer buffer = new StringBuffer(encoded.length());
while (matcher.find()) {
String replacement = matcher.group(0);
if ("+".equals(replacement)) {
replacement = "%20";
} else if ("*".equals(replacement)) {
replacement = "%2A";
} else if ("%7E".equals(replacement)) {
replacement = "~";
} else if (path && "%2F".equals(replacement)) {
replacement = "/";
}
matcher.appendReplacement(buffer, replacement);
}
matcher.appendTail(buffer);
return buffer.toString();
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
/**
* Searches for a jvm pid in the output from "jcmd -l".
*
* Example output from jcmd is:
* 12498 sun.tools.jcmd.JCmd -l
* 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
*
* @param key A regular expression to search for.
* @return The found pid, or -1 if Enot found.
* @throws Exception If multiple matching jvms are found.
*/
public static int tryFindJvmPid(String key) throws Throwable {
OutputAnalyzer output = null;
try {
JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
jcmdLauncher.addToolArg("-l");
output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
output.shouldHaveExitValue(0);
// Search for a line starting with numbers (pid), follwed by the key.
Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
Matcher matcher = pattern.matcher(output.getStdout());
int pid = -1;
if (matcher.find()) {
pid = Integer.parseInt(matcher.group(1));
System.out.println("findJvmPid.pid: " + pid);
if (matcher.find()) {
throw new Exception("Found multiple JVM pids for key: " + key);
}
}
return pid;
} catch (Throwable t) {
System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
throw t;
}
}
private String getAlternativeType(String alternativeString) {
String type = "";
// Content between Braces; Braces are escaped using double \\
Pattern patternType = Pattern.compile("\\(([^)]+)\\)$");
Matcher matcherType = patternType.matcher(alternativeString);
if (matcherType.find()) {
type = matcherType.group(1);
}
return type;
}
public static List<Node> getNodesInfo(String src) throws UnsupportedEncodingException {
List<Node> result = new ArrayList<Node>();
if (src != null)
{
Pattern pattern = Pattern.compile("5:nodes(.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(src);
String nodesInfoStr = null;
if (matcher.find())
{
nodesInfoStr = matcher.group(1);
}
if (nodesInfoStr != null)
{
int start = nodesInfoStr.indexOf(":");
int nodesInfoLength = Integer.parseInt(nodesInfoStr.substring(0, start));
byte[] nodesInfo = new byte[nodesInfoLength];
nodesInfoStr = nodesInfoStr.substring(start + 1);
try {
byte[] nodesInfoSrc = nodesInfoStr.getBytes("utf-8");
for (int i = 0; i < nodesInfoLength; i++)
{
nodesInfo[i] = nodesInfoSrc[i];
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < nodesInfoLength / SpiderConstant.NODE_INFO_LENGTH_ON_DHT; i++)
{
Node node;
byte[] nodeId = new byte[20];
String nodeIp;
byte[] nodeIpBytes = new byte[4];
int nodePort;
byte[] nodePortBytes = new byte[2];
for (int j = i * SpiderConstant.NODE_INFO_LENGTH_ON_DHT; j < (i + 1) * SpiderConstant.NODE_INFO_LENGTH_ON_DHT; j++)
{
if (j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT <= SpiderConstant.NODE_INFO_ID_LAST_INDEX)
{
nodeId[j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT] = nodesInfo[j];
}
if (SpiderConstant.NODE_INFO_ID_LAST_INDEX < j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT &&
j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT <= SpiderConstant.NODE_INFO_IP_LAST_INDEX)
{
nodeIpBytes[j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT - SpiderConstant.NODE_INFO_ID_LAST_INDEX - 1] = nodesInfo[j];
}
if (SpiderConstant.NODE_INFO_IP_LAST_INDEX < j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT &&
j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT <= SpiderConstant.NODE_INFO_PORT_LAST_INDEX)
{
nodePortBytes[j % SpiderConstant.NODE_INFO_LENGTH_ON_DHT - SpiderConstant.NODE_INFO_IP_LAST_INDEX - 1] = nodesInfo[j];
}
}
long ip_temp = Long.parseLong(bytesToHexString(nodeIpBytes), 16);
nodeIp = long2IpAdress(ip_temp);
nodePort = Integer.parseInt(bytesToHexString(nodePortBytes), 16);
node = new Node(nodeId, nodeIp, nodePort);
result.add(node);
}
}
}
return result;
}
/**
* Checks that a file in the default downloaded files folder matches the given regexp.
*
* @param file
* The name of the file
* @param encoding
* The file encoding
* @param regexp
* The pattern to match
* @param conditions
* List of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
* @throws FailureException
* if the scenario encounters a functional error
* @throws TechnicalException
* is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
* Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_FILE_NOT_MATCHES} message (with screenshot, no exception)
*/
@Conditioned
@Alors("Le fichier {string} encodé en {string} vérifie {string}(\\?)")
@Then("The file {string} encoded in {string} matches {string}(\\?)")
public void checkFile(String file, String encoding, String regexp, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException {
try {
final Matcher m = Pattern.compile(regexp)
.matcher(FileUtils.readFileToString(new File(System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER + File.separator + file), encoding));
if (!m.find()) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_FILE_NOT_MATCHES), file, regexp), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
} catch (final IOException e) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_FILE_NOT_FOUND), file), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
}