下面列出了java.util.regex.Matcher#group ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Parse a jolokia property
* @param converter the jolokia converter to use
* @param key key
* @param object value
*/
void parse(final JolokiaConverter converter, final Object key, final Object object) {
if (logger.isTraceEnabled()) {
logger.trace("Processing returned JSON Key {} with value: {}", key, object);
}
String jolokiaPropertyName = "";
if (key instanceof String) {
String tmp = (String) key;
logger.trace("Checking property name/group {}", tmp);
Pattern pattern = Pattern.compile(".*name=(.*),.*");
Matcher matcher = pattern.matcher(tmp);
if (matcher.matches()) {
jolokiaPropertyName = matcher.group(1);
logger.trace("Reading property name/group '{}'", jolokiaPropertyName);
} else {
jolokiaPropertyName = tmp;
}
}
converter.convert(jolokiaPropertyName, object);
}
/**
*
* @param input a comma-separated list of longitude,latitude pairs specifying a set of bounding boxes,
* with the southwest corner of the bounding box coming first
*
* @return a list of the Location instances represented by the provided input
*/
public static List<Location> parseLocations(final String input) {
final List<Location> locations = new ArrayList<>();
final Matcher locationsMatcher = LOCATIONS_PATTERN.matcher(input);
if (locationsMatcher.matches()) {
Matcher locationMatcher = LOCATION_PATTERN.matcher(input);
while (locationMatcher.find()) {
final String location = locationMatcher.group();
locations.add(parseLocation(location));
}
} else {
throw new IllegalStateException("The provided location string was invalid.");
}
return locations;
}
public String getDatabase(){
String table = conf.get(CLI_P_TABLE);
String database;
if(null != table && table.contains(".") && !table.endsWith(".")){
database = table.substring(0, table.indexOf("."));
}else{
Matcher m = urlRegexp.matcher(getConnectUrl());
if (m.find()) {
if (m.group(3) != null) {
database = m.group(3);
} else {
database = DEFAULT_DATABASE;
}
} else {
throw new IllegalArgumentException("Incorrect ClickHouse jdbc url: " + getConnectUrl());
}
}
return database;
}
static String extractCharset(File dir, String filename) throws IOException {
if(filename.contains("fra")){
log.info("\n");
}
File metaFile = new File(dir,filename.replace("text","meta.txt"));
FileInputStream fileIn = new FileInputStream(metaFile);
InputStreamReader isReader = new InputStreamReader(fileIn);
BufferedReader bufReader = new BufferedReader(isReader);
try {
while (true) {
String line = bufReader.readLine();
Pattern pattern = Pattern.compile("content encoding\\s+(\\S+)$");
Matcher matcher = pattern.matcher(line);
if (!matcher.find()) continue;
bufReader.close();
return matcher.group(1);
}
}
catch(Exception ex){
return "utf-8";
}
}
public String match(String agentString) {
Matcher matcher = pattern.matcher(agentString);
if (!matcher.find()) {
return null;
}
String family = null;
if (familyReplacement != null) {
if (familyReplacement.contains("$1")
&& matcher.groupCount() >= 1
&& matcher.group(1) != null) {
family = familyReplacement.replaceFirst("\\$1",
Matcher.quoteReplacement(matcher.group(1)));
} else {
family = familyReplacement;
}
} else if (matcher.groupCount() >= 1) {
family = matcher.group(1);
}
return family;
}
@Override
public void processNewLines(String[] lines) {
for (String line : lines) {
if (!line.isEmpty()) {
if (line.startsWith(SUCCESS_OUTPUT)) {
mErrorMessage = null;
} else {
Matcher m = FAILURE_PATTERN.matcher(line);
if (m.matches()) {
mErrorMessage = m.group(1);
} else {
mErrorMessage = "Unknown failure";
}
}
}
}
}
public Element(String name, String id) {
// id
final Matcher matcher = sIdPattern.matcher(id);
if (matcher.find() && matcher.groupCount() > 0) {
this.id = matcher.group(2);
String androidNS = matcher.group(1);
this.isAndroidNS = !(androidNS == null || androidNS.length() == 0);
}
// name
String[] packages = name.split("\\.");
if (packages.length > 1) {
this.nameFull = name;
this.name = packages[packages.length - 1];
} else {
this.nameFull = null;
this.name = name;
}
this.fieldName = getFieldName();
}
private String getDbRealAddress(String url, String dsType) throws Exception {
Matcher matcher;
Matcher matcherServiceName = null;
String host;
String port;
String resultOri = "";
String resultIp = "";
String serviceName = null;
if (dsType.equalsIgnoreCase("oracle")) {
matcher = ORACLE_URL_PATTERN.matcher(url);
matcherServiceName = ORACLE_SERVICE_PATTERN.matcher(url);
if (matcherServiceName.find()) {
serviceName = matcherServiceName.group(1);
}
} else {
matcher = MYSQL_URL_PATTERN.matcher(StringUtils.lowerCase(url));
}
while (matcher.find()) {
host = matcher.group(1);
port = matcher.group(2);
if (StringUtils.isNotBlank(resultOri)) {
resultOri = resultOri + "," + host + ":" + port;
resultIp = resultIp + "," + getIpByHostName(host) + ":" + port;
} else {
resultOri = host + ":" + port;
resultIp = getIpByHostName(host) + ":" + port;
}
if (serviceName != null) {
resultOri = resultOri + ":" + matcherServiceName.group(1);
resultIp = resultIp + ":" + matcherServiceName.group(1);
}
}
return resultOri + "&" + resultIp;
}
private static void cleanupModifier(StringBuffer result, String modifier) {
Matcher m = FUZZY_MODIFIDER.matcher(modifier);
if (m.matches()) {
modifier = m.group(1);
}
for (int i = 0; i < modifier.length(); i++) {
char c = modifier.charAt(i);
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z') || c == '_' || c == '-') {
result.append(c);
}
}
}
/**
* Parses a String containing zero or more PEM-encoded X509 certificates into an array of {@link X509Certificate}.
* Everything outside of BEGIN CERTIFICATE and END CERTIFICATE lines will be ignored.
*
* @param pemEncodedCAs a String containing PEM-encoded certficiates
* @return array containing certificates in the String
*/
public static X509Certificate[] readX509CertificatesFromPem(String pemEncodedCAs) {
List<X509Certificate> certificates = new ArrayList<>(500);
Matcher pemMatcher = CA_PEM_PATTERN.matcher(pemEncodedCAs);
while (pemMatcher.find()) {
String singleCAPem = pemMatcher.group();
X509Certificate certificate = readSingleX509Certificate(singleCAPem);
certificates.add(certificate);
}
return certificates.toArray(new X509Certificate[0]);
}
/**
* Read process info for the running Application.
* The Application writes its info to a file with this format:
* shutdownPort=42994
* pid=19597
* done
*
* The final "done" is used to make sure the complete file has been written
* before we try to read it.
* This function will wait until the file is available.
*
* @param filename Path to file to read.
* @return The ProcessInfo containing pid and shutdownPort.
*/
public static ProcessInfo readProcessInfo(String filename) throws Throwable {
System.out.println("Reading port and pid from file: " + filename);
File file = new File(filename);
String content = null;
// Read file or wait for it to be created.
while (true) {
content = readFile(file);
if (content != null && content.indexOf("done") >= 0) {
break;
}
Thread.sleep(100);
}
ProcessInfo info = new ProcessInfo();
// search for a line with format: key=nnn
Pattern pattern = Pattern.compile("(\\w*)=([0-9]+)\\r?\\n");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
String key = matcher.group(1);
int value = Integer.parseInt(matcher.group(2));
if ("pid".equals(key)) {
info.pid = value;
} else if ("shutdownPort".equals(key)) {
info.shutdownPort = value;
}
}
System.out.println("processInfo.pid:" + info.pid);
System.out.println("processInfo.shutdownPort:" + info.shutdownPort);
return info;
}
private static String findDate(String str) {
Pattern pattern = Pattern.compile("[0-9]{4}_[0-9]{2}_[0-9]{2}");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
return matcher.group();
}
return "";
}
/**
* Create an image name with a tag. If a tag is provided (i.e. is not null) then this tag is used.
* Otherwise the tag of the provided name is used (if any).
*
* @param fullName The fullname of the image in Docker format. I
* @param givenTag tag to use. Can be null in which case the tag specified in fullName is used.
*/
public ImageName(String fullName, String givenTag) {
if (fullName == null) {
throw new NullPointerException("Image name must not be null");
}
// set digest to null as default
digest = null;
// check if digest is part of fullName, if so -> extract it
if(fullName.contains("@sha256")) { // Of it contains digest
String[] digestParts = fullName.split("@");
digest = digestParts[1];
fullName = digestParts[0];
}
// check for tag
Pattern tagPattern = Pattern.compile("^(.+?)(?::([^:/]+))?$");
Matcher matcher = tagPattern.matcher(fullName);
if (!matcher.matches()) {
throw new IllegalArgumentException(fullName + " is not a proper image name ([registry/][repo][:port]");
}
// extract tag if it exists
tag = givenTag != null ? givenTag : matcher.group(2);
String rest = matcher.group(1);
// extract registry, repository, user
parseComponentsBeforeTag(rest);
/*
* set tag to latest if tag AND digest are null
* if digest is not null but tag is -> leave it!
* -> in case of "[email protected]" it is not required to get resolved to "latest"
*/
if (tag == null && digest == null) {
tag = "latest";
}
doValidate();
}
@NotNull
private static Module.Key parseModuleKey(String streamName, String moduleName) {
String versionAndVersionType = streamName.replace(moduleName + "-", "");
Matcher matcher = Pattern.compile("(.*)-([^-]+)$").matcher(versionAndVersionType);
if (!matcher.matches()) {
throw new IllegalArgumentException(INVALID_STREAM_NAME_ERROR_MSG);
}
TemplateContainer.VersionType versionType;
try {
versionType = TemplateContainer.VersionType.fromMinimizedForm(matcher.group(2));
} catch (InvalidParameterException e) {
throw new IllegalArgumentException(INVALID_STREAM_NAME_ERROR_MSG);
}
return new Module.Key(moduleName, matcher.group(1), versionType);
}
private void useReleases( ModifiedPomXMLEventReader pom, MavenProject project )
throws XMLStreamException, MojoExecutionException, ArtifactMetadataRetrievalException
{
String version = project.getVersion();
Matcher versionMatcher = matchSnapshotRegex.matcher( version );
if ( versionMatcher.matches() )
{
String releaseVersion = versionMatcher.group( 1 );
VersionRange versionRange;
try
{
versionRange = VersionRange.createFromVersionSpec( releaseVersion );
}
catch ( InvalidVersionSpecificationException e )
{
throw new MojoExecutionException( "Invalid version range specification: " + version, e );
}
Artifact artifact = artifactFactory.createDependencyArtifact( getProject().getParent().getGroupId(),
getProject().getParent().getArtifactId(),
versionRange, "pom", null, null );
if ( !isIncluded( artifact ) )
{
return;
}
getLog().debug( "Looking for a release of " + toString( project ) );
// Force releaseVersion version because org.apache.maven.artifact.metadata.MavenMetadataSource does not
// retrieve release version if provided snapshot version.
artifact.setVersion( releaseVersion );
ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false );
if ( !allowRangeMatching ) // standard behaviour
{
if ( versions.containsVersion( releaseVersion ) )
{
if ( PomHelper.setProjectParentVersion( pom, releaseVersion ) )
{
getLog().info( "Updated " + toString( project ) + " to version " + releaseVersion );
}
}
else if ( failIfNotReplaced )
{
throw new NoSuchElementException( "No matching release of " + toString( project )
+ " found for update." );
}
}
else
{
ArtifactVersion finalVersion = null;
for ( ArtifactVersion proposedVersion : versions.getVersions( false ) )
{
if ( proposedVersion.toString().startsWith( releaseVersion ) )
{
getLog().debug( "Found matching version for " + toString( project ) + " to version "
+ releaseVersion );
finalVersion = proposedVersion;
}
}
if ( finalVersion != null )
{
if ( PomHelper.setProjectParentVersion( pom, finalVersion.toString() ) )
{
getLog().info( "Updated " + toString( project ) + " to version " + finalVersion.toString() );
}
}
else
{
getLog().info( "No matching release of " + toString( project ) + " to update via rangeMatching." );
if ( failIfNotReplaced )
{
throw new NoSuchElementException( "No matching release of " + toString( project )
+ " found for update via rangeMatching." );
}
}
}
}
}
public static void main(String[] args) throws Exception {
String[][] kdcs = {
{"simple.host", null}, // These are legal settings
{"simple.host", ""},
{"simple.host", "8080"},
{"0.0.0.1", null},
{"0.0.0.1", ""},
{"0.0.0.1", "8080"},
{"1::1", null},
{"[1::1]", null},
{"[1::1]", ""},
{"[1::1]", "8080"},
{"[1::1", null}, // Two illegal settings
{"[1::1]abc", null},
};
// Prepares a krb5.conf with every kind of KDC settings
PrintStream out = new PrintStream(new FileOutputStream("ipv6.conf"));
out.println("[libdefaults]");
out.println("default_realm = V6");
out.println("kdc_timeout = 1");
out.println("[realms]");
out.println("V6 = {");
for (String[] hp: kdcs) {
if (hp[1] != null) out.println(" kdc = "+hp[0]+":"+hp[1]);
else out.println(" kdc = " + hp[0]);
}
out.println("}");
out.close();
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.krb5.conf", "ipv6.conf");
ByteArrayOutputStream bo = new ByteArrayOutputStream();
PrintStream po = new PrintStream(bo);
PrintStream oldout = System.out;
System.setOut(po);
try {
Subject subject = new Subject();
Krb5LoginModule krb5 = new Krb5LoginModule();
Map<String, String> map = new HashMap<>();
Map<String, Object> shared = new HashMap<>();
map.put("debug", "true");
map.put("doNotPrompt", "true");
map.put("useTicketCache", "false");
map.put("useFirstPass", "true");
shared.put("javax.security.auth.login.name", "any");
shared.put("javax.security.auth.login.password", "any".toCharArray());
krb5.initialize(subject, null, shared, map);
krb5.login();
} catch (Exception e) {
// Ignore
}
po.flush();
System.setOut(oldout);
BufferedReader br = new BufferedReader(new StringReader(
new String(bo.toByteArray())));
int cc = 0;
Pattern r = Pattern.compile(".*KrbKdcReq send: kdc=(.*) UDP:(\\d+),.*");
String line;
while ((line = br.readLine()) != null) {
Matcher m = r.matcher(line.subSequence(0, line.length()));
if (m.matches()) {
System.out.println("------------------");
System.out.println(line);
String h = m.group(1), p = m.group(2);
String eh = kdcs[cc][0], ep = kdcs[cc][1];
if (eh.charAt(0) == '[') {
eh = eh.substring(1, eh.length()-1);
}
System.out.println("Expected: " + eh + " : " + ep);
System.out.println("Actual: " + h + " : " + p);
if (!eh.equals(h) ||
(ep == null || ep.length() == 0) && !p.equals("88") ||
(ep != null && ep.length() > 0) && !p.equals(ep)) {
throw new Exception("Mismatch");
}
cc++;
}
}
if (cc != kdcs.length - 2) { // 2 illegal settings at the end
throw new Exception("Not traversed");
}
}
@Override
boolean matchesCachedFile(final Matcher matcher, final String url) {
final String hash = matcher.group("hash");
return url.hashCode() == Integer.parseInt(hash);
}
protected String fixMissingNamespaces(String descriptorXml, DescriptorBindingException ex) {
// Windows: org.fourthline.cling.binding.xml.DescriptorBindingException: Could not parse device descriptor: org.seamless.xml.ParserException: org.xml.sax.SAXParseException: The prefix "dlna" for element "dlna:X_DLNADOC" is not bound.
// Android: org.xmlpull.v1.XmlPullParserException: undefined prefix: dlna (position:START_TAG <{null}dlna:X_DLNADOC>@19:17 in [email protected])
// We can only handle certain exceptions, depending on their type and message
Throwable cause = ex.getCause();
if (!((cause instanceof SAXParseException) || (cause instanceof ParserException)))
return null;
String message = cause.getMessage();
if (message == null)
return null;
Pattern pattern = Pattern.compile("The prefix \"(.*)\" for element"); // Windows
Matcher matcher = pattern.matcher(message);
if (!matcher.find() || matcher.groupCount() != 1) {
pattern = Pattern.compile("undefined prefix: ([^ ]*)"); // Android
matcher = pattern.matcher(message);
if (!matcher.find() || matcher.groupCount() != 1)
return null;
}
String missingNS = matcher.group(1);
log.warning("Fixing missing namespace declaration for: " + missingNS);
// Extract <root> attributes
pattern = Pattern.compile("<root([^>]*)");
matcher = pattern.matcher(descriptorXml);
if (!matcher.find() || matcher.groupCount() != 1) {
log.fine("Could not find <root> element attributes");
return null;
}
String rootAttributes = matcher.group(1);
log.fine("Preserving existing <root> element attributes/namespace declarations: " + matcher.group(0));
// Extract <root> body
pattern = Pattern.compile("<root[^>]*>(.*)</root>", Pattern.DOTALL);
matcher = pattern.matcher(descriptorXml);
if (!matcher.find() || matcher.groupCount() != 1) {
log.fine("Could not extract body of <root> element");
return null;
}
String rootBody = matcher.group(1);
// Add missing namespace, it only matters that it is defined, not that it is correct
return "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<root "
+ String.format("xmlns:%s=\"urn:schemas-dlna-org:device-1-0\"", missingNS) + rootAttributes + ">"
+ rootBody
+ "</root>";
// TODO: Should we match different undeclared prefixes with their correct namespace?
// So if it's "dlna" we use "urn:schemas-dlna-org:device-1-0" etc.
}
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
checkArguments(args);
StringBuffer sb = new StringBuffer();
for (Term term : args) {
if (!term.isString()) {
continue;
}
StringTerm st = (StringTerm) term;
Matcher matcher = regex.matcher(st.getString());
while (matcher.find()) {
//System.out.println("I found the text \""+matcher.group()+ "\"starting at index "+matcher.start()+ " and ending at index "+matcher.end());
String sVar = matcher.group();
sVar = sVar.substring(2, sVar.length() - 1);
try {
Term t = null;
if (sVar.startsWith("_") && sVar.length() > 1) // deals with unnamed vars, where we cannot use parseTerm
t = new UnnamedVar( Integer.valueOf( sVar.substring(1)));
else
t = ASSyntax.parseTerm(sVar);
//We use t.apply to evaluate any logical or arithmetic expression in Jason
t = t.capply(un);
matcher.appendReplacement(sb, t.isString() ? ((StringTerm)t).getString() : t.toString());
} catch (ParseException pe) {
// TODO: handle exception
// TODO: Decide whether or not we should ignore the exception and print the call instead
// Right now, if I get a parse error from ASSyntax, I just print the original escaped
// sequence, so a user can see that his/her expression was problematic
matcher.appendReplacement(sb, "#{"+sVar+"}");
}
}
matcher.appendTail(sb);
}
if (args[args.length - 1].isVar()) {
StringTerm stRes = new StringTermImpl(sb.toString());
return un.unifies(stRes, args[args.length - 1]);
} else {
ts.getLogger().info(sb.toString());
return true;
}
}
public RangeExpression(final Matcher m, final int field) throws ParseException {
super(field);
startWeekDay = m.group(1);
endWeekDay = m.group(2);
if (field == Calendar.DAY_OF_MONTH) {
final Matcher startWeekDayMatcher = WEEKDAY.matcher(m.group(1));
final Matcher endWeekDayMatcher = WEEKDAY.matcher(m.group(2));
final Matcher startDaysFromLastDayMatcher = DAYS_TO_LAST.matcher(m.group(1));
final Matcher endDaysFromLastDayMatcher = DAYS_TO_LAST.matcher(m.group(2));
if (startWeekDayMatcher.matches()) {
startWeekdayExpr = new WeekdayExpression(startWeekDayMatcher);
}
if (endWeekDayMatcher.matches()) {
endWeekdayExpr = new WeekdayExpression(endWeekDayMatcher);
}
if (startDaysFromLastDayMatcher.matches()) {
startDaysFromLastDayExpr = new DaysFromLastDayExpression(startDaysFromLastDayMatcher);
}
if (endDaysFromLastDayMatcher.matches()) {
endDaysFromLastDayExpr = new DaysFromLastDayExpression(endDaysFromLastDayMatcher);
}
if (startWeekdayExpr != null || endWeekdayExpr != null || startDaysFromLastDayExpr != null
|| endDaysFromLastDayExpr != null || startWeekDay.equals(LAST_IDENTIFIER) || endWeekDay.equals(LAST_IDENTIFIER)) {
isDynamicRangeExpression = true;
return;
}
}
//not a dynamic range expression, go ahead to init start and end values without a calendar
initStartEndValues(null);
}