本文整理匯總了Java中java.text.ParsePosition.setIndex方法的典型用法代碼示例。如果您正苦於以下問題:Java ParsePosition.setIndex方法的具體用法?Java ParsePosition.setIndex怎麽用?Java ParsePosition.setIndex使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.text.ParsePosition
的用法示例。
在下文中一共展示了ParsePosition.setIndex方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: parse
import java.text.ParsePosition; //導入方法依賴的package包/類
@Override
public Date parse(final String source, final ParsePosition pos) {
final int offset = pos.getIndex();
final Matcher matcher = parsePattern.matcher(source.substring(offset));
if (!matcher.lookingAt()) {
return null;
}
// timing tests indicate getting new instance is 19% faster than cloning
final Calendar cal = Calendar.getInstance(timeZone, locale);
cal.clear();
for (int i = 0; i < strategies.length; ) {
final Strategy strategy = strategies[i++];
strategy.setCalendar(this, cal, matcher.group(i));
}
pos.setIndex(offset + matcher.end());
return cal.getTime();
}
示例2: parseReference
import java.text.ParsePosition; //導入方法依賴的package包/類
public String parseReference(String text, ParsePosition pos, int limit) {
int start = pos.getIndex();
int i = start;
String result = "";
while (i < limit) {
int c = UTF16.charAt(text, i);
if ((i == start && !UCharacter.isUnicodeIdentifierStart(c))
|| !UCharacter.isUnicodeIdentifierPart(c)) {
break;
}
i += UTF16.getCharCount(c);
}
if (i == start) { // No valid name chars
return result; // Indicate failure with empty string
}
pos.setIndex(i);
result = text.substring(start, i);
return result;
}
示例3: parse
import java.text.ParsePosition; //導入方法依賴的package包/類
protected static final Date parse(SimpleDateFormat parser, ParsePosition pos, String parsePattern, String txt) {
String pattern = parsePattern;
if (parsePattern.endsWith("ZZ")) {
pattern = pattern.substring(0, pattern.length() - 1);
}
parser.applyPattern(pattern);
pos.setIndex(0);
String str2 = txt;
if (parsePattern.endsWith("ZZ")) {
str2 = txt.replaceAll("([-+][0-9][0-9]):([0-9][0-9])$", "$1$2");
}
final Date date = parser.parse(str2, pos);
if (date != null && pos.getIndex() == str2.length()) {
return date;
}
return null;
}
示例4: match
import java.text.ParsePosition; //導入方法依賴的package包/類
/**
* Match text with the prefix tree.
*
* @param text the input text to parse, not null
* @param pos the position to start parsing at, from 0 to the text
* length. Upon return, position will be updated to the new parse
* position, or unchanged, if no match found.
* @return the resulting string, or null if no match found.
*/
public String match(CharSequence text, ParsePosition pos) {
int off = pos.getIndex();
int end = text.length();
if (!prefixOf(text, off, end)){
return null;
}
off += key.length();
if (child != null && off != end) {
PrefixTree c = child;
do {
if (isEqual(c.c0, text.charAt(off))) {
pos.setIndex(off);
String found = c.match(text, pos);
if (found != null) {
return found;
}
break;
}
c = c.sibling;
} while (c != null);
}
pos.setIndex(off);
return value;
}
示例5: main
import java.text.ParsePosition; //導入方法依賴的package包/類
public static void main(String[] args) {
String date = "13 Jan 2005 21:45:34 ABC";
String format = "dd MMM yyyy HH:mm:ss z";
ParsePosition pp = new ParsePosition(0);
pp.setIndex(0);
SimpleDateFormat sd = new SimpleDateFormat(format, Locale.ENGLISH);
Date d = sd.parse(date, pp);
int errorIndex = pp.getErrorIndex();
if (errorIndex == 21) {
System.out.println(": passed");
} else {
System.out.println(": failed");
throw new RuntimeException("Failed with wrong index: " + errorIndex);
}
}
示例6: parseUnresolved0
import java.text.ParsePosition; //導入方法依賴的package包/類
private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) {
Objects.requireNonNull(text, "text");
Objects.requireNonNull(position, "position");
DateTimeParseContext context = new DateTimeParseContext(this);
int pos = position.getIndex();
pos = printerParser.parse(context, text, pos);
if (pos < 0) {
position.setErrorIndex(~pos); // index not updated from input
return null;
}
position.setIndex(pos); // errorIndex not updated from input
return context;
}
示例7: parseChoiceArgument
import java.text.ParsePosition; //導入方法依賴的package包/類
private static double parseChoiceArgument(
MessagePattern pattern, int partIndex,
String source, ParsePosition pos) {
// find the best number (defined as the one with the longest parse)
int start = pos.getIndex();
int furthest = start;
double bestNumber = Double.NaN;
double tempNumber = 0.0;
while (pattern.getPartType(partIndex) != Part.Type.ARG_LIMIT) {
tempNumber = pattern.getNumericValue(pattern.getPart(partIndex));
partIndex += 2; // skip the numeric part and ignore the ARG_SELECTOR
int msgLimit = pattern.getLimitPartIndex(partIndex);
int len = matchStringUntilLimitPart(pattern, partIndex, msgLimit, source, start);
if (len >= 0) {
int newIndex = start + len;
if (newIndex > furthest) {
furthest = newIndex;
bestNumber = tempNumber;
if (furthest == source.length()) {
break;
}
}
}
partIndex = msgLimit + 1;
}
if (furthest == start) {
pos.setErrorIndex(start);
} else {
pos.setIndex(furthest);
}
return bestNumber;
}
示例8: processSet
import java.text.ParsePosition; //導入方法依賴的package包/類
private int processSet(String regex, int i, StringBuilder result, UnicodeSet temp, ParsePosition pos) {
try {
pos.setIndex(i);
UnicodeSet x = temp.clear().applyPattern(regex, pos, symbolTable, 0);
x.complement().complement(); // hack to fix toPattern
result.append(x.toPattern(false));
i = pos.getIndex() - 1; // allow for the loop increment
return i;
} catch (Exception e) {
throw (IllegalArgumentException) new IllegalArgumentException("Error in " + regex).initCause(e);
}
}
示例9: parse
import java.text.ParsePosition; //導入方法依賴的package包/類
/**
* This method converts a Roman Numeral string to a long integer. It does
* not check that the string is in the correct format - for some incorrectly
* formatted numbers, i.e. iix, it will produce a number. For others, it
* will throw an exception.
*
* @param s string of Roman Numerals
* @param parsePosition the place to start parsing
* @return A Long object containing the parsed Roman numeral
*/
@Override
public Number parse(String text, ParsePosition parsePosition)
{
String s = text.substring(parsePosition.getIndex());
long tot = 0, max = 0;
char ch[] = s.toUpperCase().toCharArray();
int i, p;
for( p = ch.length - 1; p >= 0; p-- )
{
for( i = 0; i < syms.size(); i++ )
{
if( syms.get(i).symbol == ch[p] )
{
if( syms.get(i).value >= max )
{
max = syms.get(i).value;
tot += max;
}
else
{
tot -= syms.get(i).value;
}
}
}
}
// say that we parsed the whole string
parsePosition.setIndex(s.length());
return tot;
}
示例10: parseDateWithLeniency
import java.text.ParsePosition; //導入方法依賴的package包/類
/**
* <p>Parses a string representing a date by trying a variety of different parsers.</p>
*
* <p>The parse will try each parse pattern in turn.
* A parse is only deemed successful if it parses the whole of the input string.
* If no parse patterns match, a ParseException is thrown.</p>
*
* @param str the date to parse, not null
* @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null
* @param lenient Specify whether or not date/time parsing is to be lenient.
* @return the parsed date
* @throws IllegalArgumentException if the date string or pattern array is null
* @throws ParseException if none of the date patterns were suitable
* @see java.util.Calender#isLenient()
*/
private static Date parseDateWithLeniency(String str, String[] parsePatterns,
boolean lenient) throws ParseException {
if (str == null || parsePatterns == null) {
throw new IllegalArgumentException("Date and Patterns must not be null");
}
SimpleDateFormat parser = new SimpleDateFormat();
parser.setLenient(lenient);
ParsePosition pos = new ParsePosition(0);
for (int i = 0; i < parsePatterns.length; i++) {
String pattern = parsePatterns[i];
// LANG-530 - need to make sure 'ZZ' output doesn't get passed to SimpleDateFormat
if (parsePatterns[i].endsWith("ZZ")) {
pattern = pattern.substring(0, pattern.length() - 1);
}
parser.applyPattern(pattern);
pos.setIndex(0);
String str2 = str;
// LANG-530 - need to make sure 'ZZ' output doesn't hit SimpleDateFormat as it will ParseException
if (parsePatterns[i].endsWith("ZZ")) {
int signIdx = indexOfSignChars(str2, 0);
while (signIdx >=0) {
str2 = reformatTimezone(str2, signIdx);
signIdx = indexOfSignChars(str2, ++signIdx);
}
}
Date date = parser.parse(str2, pos);
if (date != null && pos.getIndex() == str2.length()) {
return date;
}
}
throw new ParseException("Unable to parse the date: " + str, -1);
}
示例11: match
import java.text.ParsePosition; //導入方法依賴的package包/類
@Override
public String match(CharSequence text, ParsePosition pos) {
int off = pos.getIndex();
int end = text.length();
int len = key.length();
int koff = 0;
while (koff < len && off < end) {
if (isLenientChar(text.charAt(off))) {
off++;
continue;
}
if (!isEqual(key.charAt(koff++), text.charAt(off++))) {
return null;
}
}
if (koff != len) {
return null;
}
if (child != null && off != end) {
int off0 = off;
while (off0 < end && isLenientChar(text.charAt(off0))) {
off0++;
}
if (off0 < end) {
PrefixTree c = child;
do {
if (isEqual(c.c0, text.charAt(off0))) {
pos.setIndex(off0);
String found = c.match(text, pos);
if (found != null) {
return found;
}
break;
}
c = c.sibling;
} while (c != null);
}
}
pos.setIndex(off);
return value;
}
示例12: parse
import java.text.ParsePosition; //導入方法依賴的package包/類
/**
* Parses the specified string, beginning at the specified position, according
* to this formatter's rules. This will match the string against all of the
* formatter's public rule sets and return the value corresponding to the longest
* parseable substring. This function's behavior is affected by the lenient
* parse mode.
* @param text The string to parse
* @param parsePosition On entry, contains the position of the first character
* in "text" to examine. On exit, has been updated to contain the position
* of the first character in "text" that wasn't consumed by the parse.
* @return The number that corresponds to the parsed text. This will be an
* instance of either Long or Double, depending on whether the result has a
* fractional part.
* @see #setLenientParseMode
* @stable ICU 2.0
*/
@Override
public Number parse(String text, ParsePosition parsePosition) {
// parsePosition tells us where to start parsing. We copy the
// text in the string from here to the end inro a new string,
// and create a new ParsePosition and result variable to use
// for the duration of the parse operation
String workingText = text.substring(parsePosition.getIndex());
ParsePosition workingPos = new ParsePosition(0);
Number tempResult = null;
// keep track of the largest number of characters consumed in
// the various trials, and the result that corresponds to it
Number result = NFRule.ZERO;
ParsePosition highWaterMark = new ParsePosition(workingPos.getIndex());
// iterate over the public rule sets (beginning with the default one)
// and try parsing the text with each of them. Keep track of which
// one consumes the most characters: that's the one that determines
// the result we return
for (int i = ruleSets.length - 1; i >= 0; i--) {
// skip private or unparseable rule sets
if (!ruleSets[i].isPublic() || !ruleSets[i].isParseable()) {
continue;
}
// try parsing the string with the rule set. If it gets past the
// high-water mark, update the high-water mark and the result
tempResult = ruleSets[i].parse(workingText, workingPos, Double.MAX_VALUE);
if (workingPos.getIndex() > highWaterMark.getIndex()) {
result = tempResult;
highWaterMark.setIndex(workingPos.getIndex());
}
// commented out because this API on ParsePosition doesn't exist in 1.1.x
// if (workingPos.getErrorIndex() > highWaterMark.getErrorIndex()) {
// highWaterMark.setErrorIndex(workingPos.getErrorIndex());
// }
// if we manage to use up all the characters in the string,
// we don't have to try any more rule sets
if (highWaterMark.getIndex() == workingText.length()) {
break;
}
// otherwise, reset our internal parse position to the
// beginning and try again with the next rule set
workingPos.setIndex(0);
}
// add the high water mark to our original parse position and
// return the result
parsePosition.setIndex(parsePosition.getIndex() + highWaterMark.getIndex());
// commented out because this API on ParsePosition doesn't exist in 1.1.x
// if (highWaterMark.getIndex() == 0) {
// parsePosition.setErrorIndex(parsePosition.getIndex() + highWaterMark.getErrorIndex());
// }
return result;
}
示例13: doParse
import java.text.ParsePosition; //導入方法依賴的package包/類
/**
* If in "by digits" mode, parses the string as if it were a string
* of individual digits; otherwise, uses the superclass function.
* @param text The string to parse
* @param parsePosition Ignored on entry, but updated on exit to point
* to the first unmatched character
* @param baseValue The partial parse result prior to entering this
* function
* @param upperBound Only consider rules with base values lower than
* this when filling in the substitution
* @param lenientParse If true, try matching the text as numerals if
* matching as words doesn't work
* @return If the match was successful, the current partial parse
* result; otherwise new Long(0). The result is either a Long or
* a Double.
*/
public Number doParse(String text, ParsePosition parsePosition, double baseValue,
double upperBound, boolean lenientParse) {
// if we're not in byDigits mode, we can just use the inherited
// doParse()
if (!byDigits) {
return super.doParse(text, parsePosition, baseValue, 0, lenientParse);
}
else {
// if we ARE in byDigits mode, parse the text one digit at a time
// using this substitution's owning rule set (we do this by setting
// upperBound to 10 when calling doParse() ) until we reach
// nonmatching text
String workText = text;
ParsePosition workPos = new ParsePosition(1);
double result;
int digit;
DigitList dl = new DigitList();
while (workText.length() > 0 && workPos.getIndex() != 0) {
workPos.setIndex(0);
digit = ruleSet.parse(workText, workPos, 10).intValue();
if (lenientParse && workPos.getIndex() == 0) {
Number n = ruleSet.owner.getDecimalFormat().parse(workText, workPos);
if (n != null) {
digit = n.intValue();
}
}
if (workPos.getIndex() != 0) {
dl.append('0'+digit);
parsePosition.setIndex(parsePosition.getIndex() + workPos.getIndex());
workText = workText.substring(workPos.getIndex());
while (workText.length() > 0 && workText.charAt(0) == ' ') {
workText = workText.substring(1);
parsePosition.setIndex(parsePosition.getIndex() + 1);
}
}
}
result = dl.count == 0 ? 0 : dl.getDouble();
result = composeRuleValue(result, baseValue);
return new Double(result);
}
}
示例14: parseOffsetLocalizedGMT
import java.text.ParsePosition; //導入方法依賴的package包/類
/**
* Returns offset from GMT(UTC) in milliseconds for the given localized GMT
* offset format string. When the given string cannot be parsed, this method
* sets the current position as the error index to <code>ParsePosition pos</code>
* and returns 0.
*
* @param text the text contains a localized GMT offset string at the position.
* @param pos the position.
* @param isShort true if this parser to try the short format first
* @param hasDigitOffset receiving if the parsed zone string contains offset digits.
* @return the offset from GMT(UTC) in milliseconds for the given localized GMT
* offset format string.
*/
private int parseOffsetLocalizedGMT(String text, ParsePosition pos, boolean isShort, Output<Boolean> hasDigitOffset) {
int start = pos.getIndex();
int offset = 0;
int[] parsedLength = {0};
if (hasDigitOffset != null) {
hasDigitOffset.value = false;
}
offset = parseOffsetLocalizedGMTPattern(text, start, isShort, parsedLength);
// For now, parseOffsetLocalizedGMTPattern handles both long and short
// formats, no matter isShort is true or false. This might be changed in future
// when strict parsing is necessary, or different set of patterns are used for
// short/long formats.
// if (parsedLength[0] == 0) {
// offset = parseOffsetLocalizedGMTPattern(text, start, !isShort, parsedLength);
// }
if (parsedLength[0] > 0) {
if (hasDigitOffset != null) {
hasDigitOffset.value = true;
}
pos.setIndex(start + parsedLength[0]);
return offset;
}
// Try the default patterns
offset = parseOffsetDefaultLocalizedGMT(text, start, parsedLength);
if (parsedLength[0] > 0) {
if (hasDigitOffset != null) {
hasDigitOffset.value = true;
}
pos.setIndex(start + parsedLength[0]);
return offset;
}
// Check if this is a GMT zero format
if (text.regionMatches(true, start, _gmtZeroFormat, 0, _gmtZeroFormat.length())) {
pos.setIndex(start + _gmtZeroFormat.length());
return 0;
}
// Check if this is a default GMT zero format
for (String defGMTZero : ALT_GMT_STRINGS) {
if (text.regionMatches(true, start, defGMTZero, 0, defGMTZero.length())) {
pos.setIndex(start + defGMTZero.length());
return 0;
}
}
// Nothing matched
pos.setErrorIndex(start);
return 0;
}
示例15: parse
import java.text.ParsePosition; //導入方法依賴的package包/類
/**
* Parses a date/time string according to the given parse position. For
* example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
* that is equivalent to Date(837039928046).
*
* <p> By default, parsing is lenient: If the input is not in the form used
* by this object's format method but can still be parsed as a date, then
* the parse succeeds. Clients may insist on strict adherence to the
* format by calling setLenient(false).
*
* <p> Note that the normal date formats associated with some calendars - such
* as the Chinese lunar calendar - do not specify enough fields to enable
* dates to be parsed unambiguously. In the case of the Chinese lunar
* calendar, while the year within the current 60-year cycle is specified,
* the number of such cycles since the start date of the calendar (in the
* ERA field of the Calendar object) is not normally part of the format,
* and parsing may assume the wrong era. For cases such as this it is
* recommended that clients parse using the parse method that takes a Calendar
* with the Calendar passed in set to the current date, or to a date
* within the era/cycle that should be assumed if absent in the format.
*
* @see #setLenient(boolean)
*
* @param text The date/time string to be parsed
*
* @param pos On input, the position at which to start parsing; on
* output, the position at which parsing terminated, or the
* start position if the parse failed.
*
* @return A Date, or null if the input could not be parsed
* @stable ICU 2.0
*/
public Date parse(String text, ParsePosition pos) {
Date result = null;
int start = pos.getIndex();
TimeZone tzsav = calendar.getTimeZone();
calendar.clear();
parse(text, calendar, pos);
if (pos.getIndex() != start) {
try {
result = calendar.getTime();
} catch (IllegalArgumentException e) {
// This occurs if the calendar is non-lenient and there is
// an out-of-range field. We don't know which field was
// illegal so we set the error index to the start.
pos.setIndex(start);
pos.setErrorIndex(start);
}
}
// Restore TimeZone
calendar.setTimeZone(tzsav);
return result;
}