下面列出了java.util.regex.MatchResult#group ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Build a group dictionary from the matched groups. <br>
* Guaranteed to have 6 keys:<br>
* <ol>
* <li><tt>Key</tt>: a key mapping (str) as used for dict interpolation, or a positional index (num as str)</li>
* <li><tt>Flags</tt>: notational flags (e.g. <tt>"#,0,+,-,<i><space></i>)</tt></li>
* <li><tt>Width</tt>: minimum width, e.g. <code>*,2</code> (optional)</li>
* <li><tt>Precision</tt>: precision specifier, e.g. <code>.*,.2</code> (optional)</li>
* <li><tt>Length</tt>: length modifier, e.g. <code>h,l,L</code> (optional)</li>
* <li><tt>Conversion</tt>: conversion specifier <code>d,i,o,u,x,X,e,E,f,F,g,G,c,r,s,%</code></li>
* </ol>
* @param matchResult
* @return the K, V mapped groups.
* @see {@link #TOKEN_PATTERN}
*/
private static Map<String, String> extractTokenGroups(final MatchResult matchResult) {
Assert.isLegal(6 == matchResult.groupCount(),
"E: match result from TOKEN_PATTERN is malformed. Group count must be 6.");
final Map<String, String> result = new HashMap<String, String>(6);
final String key = matchResult.group(1);
final String flags = matchResult.group(2);
final String width = matchResult.group(3);
final String precision = matchResult.group(4);
final String length = matchResult.group(5);
final String conversion = matchResult.group(6);
result.put("Key", key);
result.put("Flags", flags);
result.put("Width", width);
result.put("Precision", precision);
result.put("Length", length);
result.put("Conversion", conversion);
return result;
}
private int parseYear(Scanner s, int defaultYear) {
if (s.hasNext(YEAR)) {
s.next(YEAR);
MatchResult mr = s.match();
if (mr.group(1) != null) {
return 1900; // systemv has min
} else if (mr.group(2) != null) {
return YEAR_MAX_VALUE;
} else if (mr.group(3) != null) {
return defaultYear;
}
return Integer.parseInt(mr.group(4));
/*
if (mr.group("min") != null) {
//return YEAR_MIN_VALUE;
return 1900; // systemv has min
} else if (mr.group("max") != null) {
return YEAR_MAX_VALUE;
} else if (mr.group("only") != null) {
return defaultYear;
}
return Integer.parseInt(mr.group("year"));
*/
}
throw new IllegalArgumentException("Unknown year: " + s.next());
}
private int parseYear(Scanner s, int defaultYear) {
if (s.hasNext(YEAR)) {
s.next(YEAR);
MatchResult mr = s.match();
if (mr.group(1) != null) {
return 1900; // systemv has min
} else if (mr.group(2) != null) {
return YEAR_MAX_VALUE;
} else if (mr.group(3) != null) {
return defaultYear;
}
return Integer.parseInt(mr.group(4));
/*
if (mr.group("min") != null) {
//return YEAR_MIN_VALUE;
return 1900; // systemv has min
} else if (mr.group("max") != null) {
return YEAR_MAX_VALUE;
} else if (mr.group("only") != null) {
return defaultYear;
}
return Integer.parseInt(mr.group("year"));
*/
}
throw new IllegalArgumentException("Unknown year: " + s.next());
}
public Uri(CharSequence value) {
if (JAR_URL.matches(value)) {
MatchResult jar = JAR_URL.match(value);
scheme = JAR_SCHEME;
authority = jar.group(1);
path = jar.group(2);
query = null;
fragment = null;
} else {
MatchResult result = RFC3986.match(value);
scheme = result.group(1);
authority = result.group(2);
path = result.group(3);
query = result.group(4);
fragment = result.group(5);
}
}
private int parseYear(Scanner s, int defaultYear) {
if (s.hasNext(YEAR)) {
s.next(YEAR);
MatchResult mr = s.match();
if (mr.group(1) != null) {
return 1900; // systemv has min
} else if (mr.group(2) != null) {
return YEAR_MAX_VALUE;
} else if (mr.group(3) != null) {
return defaultYear;
}
return Integer.parseInt(mr.group(4));
/*
if (mr.group("min") != null) {
//return YEAR_MIN_VALUE;
return 1900; // systemv has min
} else if (mr.group("max") != null) {
return YEAR_MAX_VALUE;
} else if (mr.group("only") != null) {
return defaultYear;
}
return Integer.parseInt(mr.group("year"));
*/
}
throw new IllegalArgumentException("Unknown year: " + s.next());
}
private int parseYear(Scanner s, int defaultYear) {
if (s.hasNext(YEAR)) {
s.next(YEAR);
MatchResult mr = s.match();
if (mr.group(1) != null) {
return 1900; // systemv has min
} else if (mr.group(2) != null) {
return YEAR_MAX_VALUE;
} else if (mr.group(3) != null) {
return defaultYear;
}
return Integer.parseInt(mr.group(4));
/*
if (mr.group("min") != null) {
//return YEAR_MIN_VALUE;
return 1900; // systemv has min
} else if (mr.group("max") != null) {
return YEAR_MAX_VALUE;
} else if (mr.group("only") != null) {
return defaultYear;
}
return Integer.parseInt(mr.group("year"));
*/
}
throw new IllegalArgumentException("Unknown year: " + s.next());
}
private static Object[] GetReplacerArguments(ExecutionContext cx, String matched, String string, int position,
MatchResult matchResult, int groupCount) {
if (groupCount > GROUP_COUNT_LIMIT
|| cx.getRuntimeContext().isEnabled(CompatibilityOption.RegExpNamedCapture)) {
return unreasonableLargeGetReplacerArguments(cx, matched, string, position, matchResult, groupCount);
}
Object[] arguments = new Object[groupCount + 3];
arguments[0] = matched;
for (int i = 1; i <= groupCount; ++i) {
String group = matchResult.group(i);
arguments[i] = (group != null ? group : UNDEFINED);
}
arguments[groupCount + 1] = position;
arguments[groupCount + 2] = string;
return arguments;
}
/**
* Build a group dictionary from the matched groups. <br>
* Guaranteed to contain 4 keys:<br>
* <ol>
* <li><tt>FormatString</tt>: the complete format string part</li>
* <li><tt>StringCharacter</tt>: the literal delimiter used (e.g. <tt>",',''',"""</tt></li>
* <li><tt>InterpolantToken</tt>: the percent sign, used to signal string interpolation</li>
* <li><tt>InterpolationValues</tt>: the values for filling in the specifier tokens in the format string.</li>
* </ol>
* @param matchResult
* @return the K, V mapped groups.
* @see {@link #FMTSTR_PATTERN}
*/
private static Map<String, String> extractFormatStringGroups(final MatchResult matchResult) {
// in a strict sense the assertion here is superfluous since the enclosing
// context in the caller already does a check if the group count is 4 and
// the execution branch in which this method is called will not be run if
// it isn't 4.
Assert.isLegal(4 == matchResult.groupCount(),
"E: Match result from FMTSTR_PATTERN is malformed. Group count must be 4.");
final Map<String, String> result = new HashMap<String, String>(4);
final String fmtString = matchResult.group(1);
final String strChar = matchResult.group(2);
final String interpToken = matchResult.group(3);
final String interpValues = matchResult.group(4);
result.put("FormatString", fmtString);
result.put("StringCharacter", strChar);
result.put("InterpolantToken", interpToken);
result.put("InterpolationValues", interpValues);
return result;
}
private int parseYear(Scanner s, int defaultYear) {
if (s.hasNext(YEAR)) {
s.next(YEAR);
MatchResult mr = s.match();
if (mr.group(1) != null) {
return 1900; // systemv has min
} else if (mr.group(2) != null) {
return YEAR_MAX_VALUE;
} else if (mr.group(3) != null) {
return defaultYear;
}
return Integer.parseInt(mr.group(4));
/*
if (mr.group("min") != null) {
//return YEAR_MIN_VALUE;
return 1900; // systemv has min
} else if (mr.group("max") != null) {
return YEAR_MAX_VALUE;
} else if (mr.group("only") != null) {
return defaultYear;
}
return Integer.parseInt(mr.group("year"));
*/
}
throw new IllegalArgumentException("Unknown year: " + s.next());
}
/**
* Returns a string extracted with a specified regular expression and a regex match group index.
*/
public static String regexpExtract(String str, String regex, int extractIndex) {
if (str == null || regex == null) {
return null;
}
try {
Matcher m = Pattern.compile(regex).matcher(str);
if (m.find()) {
MatchResult mr = m.toMatchResult();
return mr.group(extractIndex);
}
} catch (Exception e) {
LOG.error(
String.format("Exception in regexpExtract('%s', '%s', '%d')", str, regex, extractIndex),
e);
}
return null;
}
/**
* Define the proxy to use for all GA tracking requests.
* <p>
* Call this static method early (before creating any tracking requests).
*
* @param proxyAddr
* "addr:port" of the proxy to use; may also be given as URL
* ("http://addr:port/").
*/
public static void setProxy(String proxyAddr)
{
if(proxyAddr != null)
{
// Split into "proxyAddr:proxyPort".
proxyAddr = null;
int proxyPort = 8080;
try(Scanner s = new Scanner(proxyAddr))
{
s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
MatchResult m = s.match();
if(m.groupCount() >= 2)
proxyAddr = m.group(2);
if(m.groupCount() >= 4 && !(m.group(4).length() == 0))
proxyPort = Integer.parseInt(m.group(4));
}
if(proxyAddr != null)
{
SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
setProxy(new Proxy(Type.HTTP, sa));
}
}
}
private Function1<MatchResult, String> matchGroup() {
return new Function1<MatchResult, String>() {
public String call(MatchResult matchResult) throws Exception {
return matchResult.group();
}
};
}
/**
* Convert the match into a map.
* <p>
* Relies on the fact that the matchingKeywords list is in the same order as the groups in the regular expression
*
* @param result
* @return map
*/
private Map processEvent(MatchResult result) {
Map map = new HashMap();
// group zero is the entire match - process all other groups
for (int i = 1; i < result.groupCount() + 1; i++) {
Object key = matchingKeywords.get(i - 1);
Object value = result.group(i);
map.put(key, value);
}
return map;
}
public static Optional<Filter> load( final MatchResult regex, final Function<String, Filter> simpleFilterLoader ) {
String match = regex.group( 1 );
if ( !match.contains( "," ) ) {
return Optional.of( simpleFilterLoader.apply( match ) );
}
final String remainder = match.substring( match.indexOf( ',' ) + 1 ).trim();
match = match.substring( 0, match.indexOf( ',' ) );
// TODO Either no optional as return or no exception below
final Filter chained = chainableFilter.load( remainder ). //
orElseThrow( () -> new IllegalArgumentException(
"Couldn't find a filter for the expression '" + remainder + "'." ) );
return Optional.of( new AllMatchFilter( simpleFilterLoader.apply( match ), chained ) );
}
private Map<String, String> parseQueryParameters(final String uri) throws BatchException {
Scanner uriScanner = new Scanner(uri).useDelimiter("\n");
Map<String, String> queryParametersMap = new HashMap<String, String>();
Pattern regex = Pattern.compile("(?:" + baseUri + "/)?" + "[^?]+" + "\\?(.*)");
if (uriScanner.hasNext(regex)) {
uriScanner.next(regex);
MatchResult uriResult = uriScanner.match();
if (uriResult.groupCount() == 1) {
String queryParams = uriResult.group(1);
Scanner queryParamsScanner = new Scanner(queryParams).useDelimiter("&");
while (queryParamsScanner.hasNext(REG_EX_QUERY_PARAMETER)) {
queryParamsScanner.next(REG_EX_QUERY_PARAMETER);
MatchResult result = queryParamsScanner.match();
if (result.groupCount() == 2) {
String systemQueryOption = result.group(1);
String value = result.group(2);
queryParametersMap.put(systemQueryOption, Decoder.decode(value));
} else {
queryParamsScanner.close();
throw new BatchException(BatchException.INVALID_QUERY_PARAMETER);
}
}
queryParamsScanner.close();
} else {
uriScanner.close();
throw new BatchException(BatchException.INVALID_URI.addContent(currentLineNumber));
}
}
uriScanner.close();
return queryParametersMap;
}
public static final PluginInfo build(File f) {
Matcher m = REGEX.matcher(f.getName());
if (m == null || !m.matches()) {
if (LOG) {
LogDebug.d(PLUGIN_TAG, "PluginInfo.build: skip, no match1, file=" + f.getAbsolutePath());
}
return null;
}
MatchResult r = m.toMatchResult();
if (r == null || r.groupCount() != 4) {
if (LOG) {
LogDebug.d(PLUGIN_TAG, "PluginInfo.build: skip, no match2, file=" + f.getAbsolutePath());
}
return null;
}
String name = r.group(1);
int low = Integer.parseInt(r.group(2));
int high = Integer.parseInt(r.group(3));
int ver = Integer.parseInt(r.group(4));
String path = f.getPath();
PluginInfo info = new PluginInfo(name, low, high, ver, TYPE_PN_INSTALLED, DownloadFileInfo.NONE_PLUGIN, path, -1, -1, -1, null);
if (LOG) {
LogDebug.d(PLUGIN_TAG, "PluginInfo.build: found plugin, name=" + info.getName()
+ " low=" + info.getLowInterfaceApi() + " high=" + info.getHighInterfaceApi()
+ " ver=" + info.getVersion());
}
return info;
}
public String replaceVariables(String raw) throws Exception {
if (raw == null) {
return null;
}
Matcher matcher = PATTERN.matcher(raw);
StringBuilder replaced = new StringBuilder();
int cur = 0;
while (matcher.find()) {
MatchResult result = matcher.toMatchResult();
replaced.append(raw.substring(cur, result.start(1)));
String name = result.group(2);
Object value = this.supplier.valueOf(name);
if (value == null) {
value = "${" + name + "}";
}
replaced.append(value);
cur = result.end();
}
replaced.append(raw.substring(cur));
return replaced.toString();
}
/**
* 通过文件名和文件类型,构建V5FileInfo对象
*
* @param f
* @param type
* @return
*/
static final DownloadFileInfo build(File f, int type) {
Matcher m = null;
String fullname = f.getName();
if (type == INCREMENT_PLUGIN) {
m = INCREMENT_REGEX.matcher(fullname);
} else if (type == SINGLE_PLUGIN) {
m = INCREMENT_SINGLE_REGEX.matcher(fullname);
} else if (type == MULTI_PLUGIN) {
m = MULTI_REGEX.matcher(fullname);
} else {
m = NORMAL_REGEX.matcher(fullname);
}
if (m == null || !m.matches()) {
if (AppConstant.LOG_V5_FILE_SEARCH) {
if (LOG) {
LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: skip, no match1, type=" + type + " file=" + f.getAbsolutePath());
}
}
return null;
}
MatchResult r = m.toMatchResult();
if (r == null || r.groupCount() != 1) {
if (AppConstant.LOG_V5_FILE_SEARCH) {
if (LOG) {
LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: skip, no match2, type=" + type + " file=" + f.getAbsolutePath());
}
}
return null;
}
if (!f.exists() || !f.isFile()) {
if (AppConstant.LOG_V5_FILE_SEARCH) {
if (LOG) {
LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: nor exist or file, file=" + f.getAbsolutePath());
}
}
return null;
}
DownloadFileInfo p = new DownloadFileInfo();
p.mName = r.group(1);
p.mFile = f;
p.mType = type;
if (LOG) {
LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: found plugin, name=" + p.mName + " file=" + f.getAbsolutePath());
}
return p;
}
@Override
protected Optional<ElementIdMatcher> load( final MatchResult matcher ) {
final String id = matcher.group( 1 );
return Optional.of( new ElementIdMatcher( id ) );
}
private void executeSaveActions(IDocument document) throws BadLocationException {
if (PydevSaveActionsPrefPage.getDateFieldActionEnabled(this)) {
final String contents = document.get();
final String fieldName = PydevSaveActionsPrefPage.getDateFieldName(this);
final String fieldPattern = String
.format("^%s(\\s*)=(\\s*[ur]{0,2}['\"]{1,3})(.+?)(['\"]{1,3})", fieldName);
final Pattern pattern = Pattern.compile(fieldPattern, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(contents);
if (matcher.find()) {
final MatchResult matchResult = matcher.toMatchResult();
if (matchResult.groupCount() == 4) {
final String spBefore = matchResult.group(1);
final String spAfterQuoteBegin = matchResult.group(2);
final String dateStr = matchResult.group(3);
final String quoteEnd = matchResult.group(4);
final String dateFormat = PydevSaveActionsPrefPage.getDateFieldFormat(this);
final Date nowDate = new Date();
final SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
try {
final Date fieldDate = ft.parse(dateStr);
// don't touch future dates
if (fieldDate.before(nowDate)) {
final String newDateStr = ft.format(nowDate);
final String replacement = fieldName + spBefore + "=" + spAfterQuoteBegin + newDateStr
+ quoteEnd;
document.replace(matchResult.start(), matchResult.end() - matchResult.start(), replacement);
}
} catch (final java.text.ParseException pe) {
// do nothing
}
}
}
}
if (PydevSaveActionsPrefPage.getSortImportsOnSave(this)) {
boolean automatic = true;
PyOrganizeImports organizeImports = new PyOrganizeImports(automatic);
try {
organizeImports.formatAll(getDocument(), this, getIFile(), true, true);
} catch (SyntaxErrorException e) {
Log.log(e);
}
}
}