下面列出了java.util.regex.Matcher#lookingAt ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns a media type for {@code string}, or null if {@code string} is not a
* well-formed media type.
*/
public static MediaType parse(String string) {
Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
if (!typeSubtype.lookingAt()) return null;
String type = typeSubtype.group(1).toLowerCase(Locale.US);
String subtype = typeSubtype.group(2).toLowerCase(Locale.US);
String charset = null;
Matcher parameter = PARAMETER.matcher(string);
for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
parameter.region(s, string.length());
if (!parameter.lookingAt()) return null; // This is not a well-formed media type.
String name = parameter.group(1);
if (name == null || !name.equalsIgnoreCase("charset")) continue;
if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
charset = parameter.group(2) != null
? parameter.group(2) // Value is a token.
: parameter.group(3); // Value is a quoted string.
}
return new MediaType(string, type, subtype, charset);
}
@Override
public Date parse(String source, ParsePosition pos) {
int offset= pos.getIndex();
Matcher matcher= parsePattern.matcher(source.substring(offset));
if(!matcher.lookingAt()) {
return null;
}
// timing tests indicate getting new instance is 19% faster than cloning
Calendar cal= Calendar.getInstance(timeZone, locale);
cal.clear();
for(int i=0; i<strategies.length;) {
Strategy strategy= strategies[i++];
strategy.setCalendar(this, cal, matcher.group(i));
}
pos.setIndex(offset+matcher.end());
return cal.getTime();
}
@Override
public Date parse(String source, ParsePosition pos) {
int offset= pos.getIndex();
Matcher matcher= parsePattern.matcher(source.substring(offset));
if(!matcher.lookingAt()) {
return null;
}
// timing tests indicate getting new instance is 19% faster than cloning
Calendar cal= Calendar.getInstance(timeZone, locale);
cal.clear();
for(int i=0; i<strategies.length;) {
Strategy strategy= strategies[i++];
strategy.setCalendar(this, cal, matcher.group(i));
}
pos.setIndex(offset+matcher.end());
return cal.getTime();
}
/**
* Returns a media type for {@code string}, or null if {@code string} is not a
* well-formed media type.
*/
public static MediaType parse(String string) {
Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
if (!typeSubtype.lookingAt()) return null;
String type = typeSubtype.group(1).toLowerCase(Locale.US);
String subtype = typeSubtype.group(2).toLowerCase(Locale.US);
String charset = null;
Matcher parameter = PARAMETER.matcher(string);
for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
parameter.region(s, string.length());
if (!parameter.lookingAt()) return null; // This is not a well-formed media type.
String name = parameter.group(1);
if (name == null || !name.equalsIgnoreCase("charset")) continue;
if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
charset = parameter.group(2) != null
? parameter.group(2) // Value is a token.
: parameter.group(3); // Value is a quoted string.
}
return new MediaType(string, type, subtype, charset);
}
@Override
public Date parse(String source, ParsePosition pos) {
int offset= pos.getIndex();
Matcher matcher= parsePattern.matcher(source.substring(offset));
if(!matcher.lookingAt()) {
return null;
}
// timing tests indicate getting new instance is 19% faster than cloning
Calendar cal= Calendar.getInstance(timeZone, locale);
cal.clear();
for(int i=0; i<strategies.length;) {
Strategy strategy= strategies[i++];
strategy.setCalendar(this, cal, matcher.group(i));
}
pos.setIndex(offset+matcher.end());
return cal.getTime();
}
@Override
public Date parse(String source, ParsePosition pos) {
int offset= pos.getIndex();
Matcher matcher= parsePattern.matcher(source.substring(offset));
if(!matcher.lookingAt()) {
return null;
}
// timing tests indicate getting new instance is 19% faster than cloning
Calendar cal= Calendar.getInstance(timeZone, locale);
cal.clear();
for(int i=0; i<strategies.length;) {
Strategy strategy= strategies[i++];
strategy.setCalendar(this, cal, matcher.group(i));
}
pos.setIndex(offset+matcher.end());
return cal.getTime();
}
private String removeNationalPrefixFromNationalNumber() {
int startOfNationalNumber = 0;
if (isNanpaNumberWithNationalPrefix()) {
startOfNationalNumber = 1;
prefixBeforeNationalNumber.append('1').append(SEPARATOR_BEFORE_NATIONAL_NUMBER);
isCompleteNumber = true;
} else if (currentMetadata.hasNationalPrefixForParsing()) {
Pattern nationalPrefixForParsing =
regexCache.getPatternForRegex(currentMetadata.getNationalPrefixForParsing());
Matcher m = nationalPrefixForParsing.matcher(nationalNumber);
// Since some national prefix patterns are entirely optional, check that a national prefix
// could actually be extracted.
if (m.lookingAt() && m.end() > 0) {
// When the national prefix is detected, we use international formatting rules instead of
// national ones, because national formatting rules could contain local formatting rules
// for numbers entered without area code.
isCompleteNumber = true;
startOfNationalNumber = m.end();
prefixBeforeNationalNumber.append(nationalNumber.substring(0, startOfNationalNumber));
}
}
String nationalPrefix = nationalNumber.substring(0, startOfNationalNumber);
nationalNumber.delete(0, startOfNationalNumber);
return nationalPrefix;
}
@Override
public <V> boolean match(final MatcherContext<V> context)
{
final InputBuffer buffer = context.getInputBuffer();
final int startIndex = context.getCurrentIndex();
final int length = buffer.length();
final CharSequence cs = buffer.subSequence(startIndex, length);
// That is a java.util.regex.Matcher!!
final Matcher matcher = pattern.matcher(cs);
final boolean ret = matcher.lookingAt();
if (ret)
context.advanceIndex(matcher.end());
return ret;
}
/**
* @param cwd
* the current working directory of the compiler at its invocation
* @see de.marw.cmake.cdt.lsp.IArglet#processArgument(IParseContext, IPath, String)
*/
protected final int processArgument(IParseContext parseContext, IPath cwd,
String argsLine, NameOptionMatcher[] optionMatchers) {
for (NameOptionMatcher oMatcher : optionMatchers) {
final Matcher matcher = oMatcher.matcher;
matcher.reset(argsLine);
if (matcher.lookingAt()) {
String name = matcher.group(oMatcher.nameGroup);
IPath path = Path.fromOSString(name);
if (!path.isAbsolute()) {
// prepend CWD
name = cwd.append(path).toOSString();
}
final ICLanguageSettingEntry entry = CDataUtil.createCIncludeFileEntry(name,
ICSettingEntry.READONLY);
parseContext.addSettingEntry(entry);
final int end = matcher.end();
return end;
}
}
return 0;// no input consumed
}
/**
* Parse the st for a double value
* MySQL compat in that illegal digits will be truncated and won't cause
* NumberFormatException
*
* @param st
* @param context
* @return
*/
public static double parseDoubleString(String st, TExecutionContext context)
{
double ret = 0;
Matcher m = DOUBLE_PATTERN.matcher(st);
if (m.lookingAt())
{
String truncated = st.substring(0, m.end());
if (!truncated.equals(st))
{
context.reportTruncate(st, truncated);
}
try
{
ret = Double.parseDouble(truncated);
}
catch (NumberFormatException e)
{
context.reportBadValue(e.getMessage());
}
}
else
context.reportBadValue(st);
return ret;
}
/**
* Initialize derived fields from defining fields.
* This is called from constructor and from readObject (de-serialization)
*
* @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
*/
private void init(Calendar definingCalendar) {
final StringBuilder regex = new StringBuilder();
final List<Strategy> collector = new ArrayList<Strategy>();
final Matcher patternMatcher = formatPattern.matcher(pattern);
if (!patternMatcher.lookingAt()) {
throw new IllegalArgumentException(
"Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
}
currentFormatField = patternMatcher.group();
Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar);
for (; ; ) {
patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
if (!patternMatcher.lookingAt()) {
nextStrategy = null;
break;
}
final String nextFormatField = patternMatcher.group();
nextStrategy = getStrategy(nextFormatField, definingCalendar);
if (currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField = nextFormatField;
currentStrategy = nextStrategy;
}
if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
throw new IllegalArgumentException("Failed to parse \"" + pattern + "\" ; gave up at index " + patternMatcher.regionStart());
}
if (currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField = null;
strategies = collector.toArray(new Strategy[collector.size()]);
parsePattern = Pattern.compile(regex.toString());
}
private @Nullable CharSequence readRegexp(@NotNull Pattern pattern) {
Matcher matcher = pattern.matcher(this);
if (matcher.lookingAt()) {
CharSequence result = subSequence(0, matcher.end());
offset += result.length();
return result;
} else {
return null;
}
}
/**
* Initialize derived fields from defining fields.
* This is called from constructor and from readObject (de-serialization)
*/
private void init() {
thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);
nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();
StringBuilder regex= new StringBuilder();
List<Strategy> collector = new ArrayList<Strategy>();
Matcher patternMatcher= formatPattern.matcher(pattern);
if(!patternMatcher.lookingAt()) {
throw new IllegalArgumentException("Invalid pattern");
}
currentFormatField= patternMatcher.group();
Strategy currentStrategy= getStrategy(currentFormatField);
for(;;) {
patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
if(!patternMatcher.lookingAt()) {
nextStrategy = null;
break;
}
String nextFormatField= patternMatcher.group();
nextStrategy = getStrategy(nextFormatField);
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= nextFormatField;
currentStrategy= nextStrategy;
}
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= null;
strategies= collector.toArray(new Strategy[collector.size()]);
parsePattern= Pattern.compile(regex.toString());
}
String fullClassNameAndPackageToClass(String full, String pkg) {
Matcher mat = PREFIX_PATTERN.matcher(full);
if (mat.lookingAt()) {
return full.substring(mat.end());
}
state.debug(DBG_DEP, "SM %s %s\n", full, pkg);
List<String> klasses = importSnippets()
.filter(isi -> !isi.isStar)
.map(isi -> isi.fullname)
.collect(toList());
for (String k : klasses) {
if (k.equals(full)) {
return full.substring(full.lastIndexOf(".")+1, full.length());
}
}
List<String> pkgs = importSnippets()
.filter(isi -> isi.isStar)
.map(isi -> isi.fullname.substring(0, isi.fullname.lastIndexOf(".")))
.collect(toList());
pkgs.add(0, "java.lang");
for (String ipkg : pkgs) {
if (!ipkg.isEmpty() && ipkg.equals(pkg)) {
return full.substring(pkg.length() + 1);
}
}
return full;
}
/**
* Append each dependency listed in the centralized Ivy versions file
* to the grandparent POM's <dependencyManagement> section.
* An <exclusion> is added for each of the artifact's dependencies,
* which are collected from the artifact's ivy.xml from the Ivy cache.
*
* Also add a version property for each dependency.
*/
private void appendAllExternalDependencies(StringBuilder dependenciesBuilder, Map<String,String> versionsMap) {
log("Loading centralized ivy versions from: " + centralizedVersionsFile, verboseLevel);
ivyCacheDir = getIvyCacheDir();
Properties versions = new InterpolatedProperties();
try (InputStream inputStream = new FileInputStream(centralizedVersionsFile);
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
versions.load(reader);
} catch (IOException e) {
throw new BuildException("Exception reading centralized versions file " + centralizedVersionsFile.getPath(), e);
}
SortedSet<Map.Entry<?,?>> sortedEntries = new TreeSet<>(new Comparator<Map.Entry<?,?>>() {
@Override public int compare(Map.Entry<?,?> o1, Map.Entry<?,?> o2) {
return ((String)o1.getKey()).compareTo((String)o2.getKey());
}
});
sortedEntries.addAll(versions.entrySet());
for (Map.Entry<?,?> entry : sortedEntries) {
String key = (String)entry.getKey();
Matcher matcher = COORDINATE_KEY_PATTERN.matcher(key);
if (matcher.lookingAt()) {
String groupId = matcher.group(1);
String artifactId = matcher.group(2);
String coordinate = groupId + ':' + artifactId;
String version = (String)entry.getValue();
versionsMap.put(coordinate + ".version", version);
if ( ! nonJarDependencies.contains(coordinate)) {
Set<String> classifiers = dependencyClassifiers.get(coordinate);
if (null != classifiers) {
for (String classifier : classifiers) {
Collection<String> exclusions = getTransitiveDependenciesFromIvyCache(groupId, artifactId, version);
appendDependencyXml
(dependenciesBuilder, groupId, artifactId, " ", version, false, false, classifier, exclusions);
}
}
}
}
}
}
@Override
public int process(IParserHandler parserHandler, String argsLine) {
for (NameOptionMatcher oMatcher : optionMatchers) {
final Matcher matcher = oMatcher.matcher;
matcher.reset(argsLine);
if (matcher.lookingAt()) {
String fname = matcher.group(oMatcher.nameGroup);
final int consumed = matcher.end();
if("<<".equals(fname)) {
// see https://github.com/15knots/cmake4eclipse/issues/94
// Handle '@<< compiler-args <<' syntax: The file '<<' does not exist, arguments come from argsline.
// so we just do not open the non-existing file
return consumed;
}
IPath path = Path.fromOSString(fname);
if (!path.isAbsolute()) {
// relative path, prepend CWD
fname = parserHandler.getCompilerWorkingDirectory().append(path).toOSString();
}
// parse file
java.nio.file.Path fpath = Paths.get(fname);
try {
String args2 = new String(Files.readAllBytes(fpath));
parserHandler.parseArguments(args2);
} catch (IOException e) {
// swallow exception for now
e.printStackTrace();
}
return consumed;
}
}
return 0;// no input consumed
}
/**
* Returns a media type for {@code string}, or null if {@code string} is not a well-formed media
* type.
*/
public static MediaType parse(String string) {
Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
if (!typeSubtype.lookingAt()) return null;
String type = typeSubtype.group(1).toLowerCase(Locale.US);
String subtype = typeSubtype.group(2).toLowerCase(Locale.US);
String charset = null;
Matcher parameter = PARAMETER.matcher(string);
for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
parameter.region(s, string.length());
if (!parameter.lookingAt()) return null; // This is not a well-formed media type.
String name = parameter.group(1);
if (name == null || !name.equalsIgnoreCase("charset")) continue;
String charsetParameter;
String token = parameter.group(2);
if (token != null) {
// If the token is 'single-quoted' it's invalid! But we're lenient and strip the quotes.
charsetParameter = (token.startsWith("'") && token.endsWith("'") && token.length() > 2)
? token.substring(1, token.length() - 1)
: token;
} else {
// Value is "double-quoted". That's valid and our regex group already strips the quotes.
charsetParameter = parameter.group(3);
}
if (charset != null && !charsetParameter.equalsIgnoreCase(charset)) {
return null; // Multiple different charsets!
}
charset = charsetParameter;
}
return new MediaType(string, type, subtype, charset);
}
protected void readLine() throws ParseException {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new ParseException(e);
}
if (line == null) {
hasMore = false;
return;
}
int lineNo = reader.getLineNumber();
Matcher matcher = pattern.matcher(line);
matcher.useTransparentBounds(true).useAnchoringBounds(false);
int pos = 0;
int endPos = line.length();
while (pos < endPos) {
matcher.region(pos, endPos);
if (matcher.lookingAt()) {
addToken(lineNo, matcher);
pos = matcher.end();
}
else
throw new ParseException("bad token at line " + lineNo);
}
queue.add(new IdToken(lineNo, Token.EOL));
}
/**
* Gets, whether the specified Matcher for the tool arguments can properly
* parse the specified command-line string. If so, the remaining arguments
* of the command-line are returned.
*
* @param matcher
* the matcher that performs the match a regular expression that
* matches the version string in the name of the tool to detect.
* @param commandLine
* the command-line to match
* @return {@code null} if the matcher did not match the tool name in the
* command-line string. Otherwise, if the tool name matches, a
* MatchResult holding the de-composed command-line is returned.
*/
private DefaultToolDetectionParticipant.MatchResult matcherMatches(Matcher matcher, String commandLine) {
matcher.reset(commandLine);
if (matcher.lookingAt()) {
return new DefaultToolDetectionParticipant.MatchResult(matcher.group(REGEX_GROUP_CMD), commandLine.substring(matcher.end()));
}
return null;
}
/**
* Attempt to match a US state beginnning at position offset in
* content. The matching state must be followed by a word
* delimiter or the end of the string, and if offset is non-zero,
* then it must also be preceded by a word delimiter.
*
* @return a MatchResult if a valid US state (or two letter code)
* was found.
*/
private static MatchResult matchState(String content, int offset) {
if (offset > 0 && WORD_DELIM.indexOf(content.charAt(offset - 1)) == -1) return null;
Matcher stateMatcher = sStateRe.matcher(content).region(offset, content.length());
return stateMatcher.lookingAt() ? stateMatcher.toMatchResult() : null;
}