Java Code Examples for java.text.ParsePosition#getIndex()
The following examples show how to use
java.text.ParsePosition#getIndex() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RBBISymbolTable.java From fitnotifications with Apache License 2.0 | 6 votes |
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; }
Example 2
Source File: Dates.java From smart-cache with Apache License 2.0 | 6 votes |
/** * 用指定的格式解析日期时间. * * @param date 时间字符串 * @param patterns 多个模式,see {@link java.text.SimpleDateFormat} * @return 如果无法解析,那么返回 {@code null} */ public static Date parse(String date, String[] patterns) { if (date == null || date.length() == 0) { return null; } date = date.trim(); for (String pattern : patterns) { SimpleDateFormat df = new SimpleDateFormat(pattern); df.setLenient(false); try { ParsePosition pp = new ParsePosition(0); Date d = df.parse(date, pp); if (d != null && pp.getIndex() == date.length()) { return d; } } catch (Exception e) { } } return null; }
Example 3
Source File: CachingDateFormat.java From alfresco-core with GNU Lesser General Public License v3.0 | 6 votes |
/** * Parses and caches date strings. * * @see java.text.DateFormat#parse(java.lang.String, * java.text.ParsePosition) */ public Date parse(String text, ParsePosition pos) { Date cached = cacheDates.get(text); if (cached == null) { Date date = super.parse(text, pos); if ((date != null) && (pos.getIndex() == text.length())) { cacheDates.put(text, date); return (Date) date.clone(); } else { return date; } } else { pos.setIndex(text.length()); return (Date) cached.clone(); } }
Example 4
Source File: DateTimeFormatterBuilder.java From jdk1.8-source-analysis with Apache License 2.0 | 6 votes |
/** * 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; }
Example 5
Source File: UnicodeSet.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Parse a property pattern. * @param chars iterator over the pattern characters. Upon return * it will be advanced to the first character after the parsed * pattern, or the end of the iteration if all characters are * parsed. * @param rebuiltPat the pattern that was parsed, rebuilt or * copied from the input pattern, as appropriate. * @param symbols TODO */ private void applyPropertyPattern(RuleCharacterIterator chars, StringBuffer rebuiltPat, SymbolTable symbols) { String patStr = chars.lookahead(); ParsePosition pos = new ParsePosition(0); applyPropertyPattern(patStr, pos, symbols); if (pos.getIndex() == 0) { syntaxError(chars, "Invalid property pattern"); } chars.jumpahead(pos.getIndex()); rebuiltPat.append(patStr.substring(0, pos.getIndex())); }
Example 6
Source File: DateTimeFormatter.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
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; }
Example 7
Source File: ExtendedMessageFormat.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Consume whitespace from the current parse position. * * @param pattern String to read * @param pos current position */ private void seekNonWs(String pattern, ParsePosition pos) { int len = 0; char[] buffer = pattern.toCharArray(); do { len = StrMatcher.splitMatcher().isMatch(buffer, pos.getIndex()); pos.setIndex(pos.getIndex() + len); } while (len > 0 && pos.getIndex() < pattern.length()); }
Example 8
Source File: ExtendedMessageFormat.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Read the argument index from the current format element * * @param pattern pattern to parse * @param pos current parse position * @return argument index */ private int readArgumentIndex(String pattern, ParsePosition pos) { int start = pos.getIndex(); seekNonWs(pattern, pos); StrBuilder result = new StrBuilder(); boolean error = false; for (; !error && pos.getIndex() < pattern.length(); next(pos)) { char c = pattern.charAt(pos.getIndex()); if (Character.isWhitespace(c)) { seekNonWs(pattern, pos); c = pattern.charAt(pos.getIndex()); if (c != START_FMT && c != END_FE) { error = true; continue; } } if ((c == START_FMT || c == END_FE) && result.length() > 0) { try { return Integer.parseInt(result.toString()); } catch (NumberFormatException e) { // we've already ensured only digits, so unless something // outlandishly large was specified we should be okay. } } error = !Character.isDigit(c); result.append(c); } if (error) { throw new IllegalArgumentException( "Invalid format argument index at position " + start + ": " + pattern.substring(start, pos.getIndex())); } throw new IllegalArgumentException( "Unterminated format element at position " + start); }
Example 9
Source File: DateUtils.java From lams with GNU General Public License v2.0 | 5 votes |
/** * <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); }
Example 10
Source File: UnicodeSet.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Parse a property pattern. * @param chars iterator over the pattern characters. Upon return * it will be advanced to the first character after the parsed * pattern, or the end of the iteration if all characters are * parsed. * @param rebuiltPat the pattern that was parsed, rebuilt or * copied from the input pattern, as appropriate. * @param symbols TODO */ private void applyPropertyPattern(RuleCharacterIterator chars, StringBuffer rebuiltPat, SymbolTable symbols) { String patStr = chars.lookahead(); ParsePosition pos = new ParsePosition(0); applyPropertyPattern(patStr, pos, symbols); if (pos.getIndex() == 0) { syntaxError(chars, "Invalid property pattern"); } chars.jumpahead(pos.getIndex()); rebuiltPat.append(patStr.substring(0, pos.getIndex())); }
Example 11
Source File: UnicodeSet.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * Parse a property pattern. * @param chars iterator over the pattern characters. Upon return * it will be advanced to the first character after the parsed * pattern, or the end of the iteration if all characters are * parsed. * @param rebuiltPat the pattern that was parsed, rebuilt or * copied from the input pattern, as appropriate. * @param symbols TODO */ private void applyPropertyPattern(RuleCharacterIterator chars, StringBuffer rebuiltPat, SymbolTable symbols) { String patStr = chars.lookahead(); ParsePosition pos = new ParsePosition(0); applyPropertyPattern(patStr, pos, symbols); if (pos.getIndex() == 0) { syntaxError(chars, "Invalid property pattern"); } chars.jumpahead(pos.getIndex()); rebuiltPat.append(patStr.substring(0, pos.getIndex())); }
Example 12
Source File: DateTimeFormatter.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
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; }
Example 13
Source File: UnitFormat.java From microMathematics with GNU General Public License v3.0 | 5 votes |
/** * Parses the text from a string to produce an object * (implements <code>java.text.Format</code>). * * @param source the string source, part of which should be parsed. * @param pos the cursor position. * @return the corresponding unit or <code>null</code> if the string * cannot be parsed. */ public final Unit<?> parseObject(String source, ParsePosition pos) { int start = pos.getIndex(); try { return parseProductUnit(source, pos); } catch (ParseException e) { pos.setIndex(start); pos.setErrorIndex(e.getErrorOffset()); return null; } }
Example 14
Source File: DateTimeFormatter.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
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; }
Example 15
Source File: MeasureFormat.java From microMathematics with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") private Object parseCompound(Number highValue, String source, ParsePosition pos) throws ParseException { Unit high = _unitFormat.parseSingleUnit(source, pos); int i = pos.getIndex(); if (i >= source.length() || Character.isWhitespace(source.charAt(i))) return measureOf(highValue, high); Measure lowMeasure = (Measure) parseObject(source, pos); Unit unit = lowMeasure.getUnit(); long l = lowMeasure.longValue(unit) + (long) high.getConverterTo(unit).convert( highValue.longValue()); return Measure.valueOf(l, unit); }
Example 16
Source File: NFSubstitution.java From fitnotifications with Apache License 2.0 | 4 votes |
/** * Dispatches to the inherited version of this function, but makes * sure that lenientParse is off. */ public Number doParse(String text, ParsePosition parsePosition, double baseValue, double upperBound, boolean lenientParse) { // we don't have to do anything special to do the parsing here, // but we have to turn lenient parsing off-- if we leave it on, // it SERIOUSLY messes up the algorithm // if withZeros is true, we need to count the zeros // and use that to adjust the parse result int zeroCount = 0; if (withZeros) { String workText = text; ParsePosition workPos = new ParsePosition(1); //int digit; while (workText.length() > 0 && workPos.getIndex() != 0) { workPos.setIndex(0); /*digit = */ruleSet.parse(workText, workPos, 1).intValue(); // parse zero or nothing at all if (workPos.getIndex() == 0) { // we failed, either there were no more zeros, or the number was formatted with digits // either way, we're done break; } ++zeroCount; 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); } } text = text.substring(parsePosition.getIndex()); // arrgh! parsePosition.setIndex(0); } // we've parsed off the zeros, now let's parse the rest from our current position Number result = super.doParse(text, parsePosition, withZeros ? 1 : baseValue, upperBound, false); if (withZeros) { // any base value will do in this case. is there a way to // force this to not bother trying all the base values? // compute the 'effective' base and prescale the value down long n = result.longValue(); long d = 1; while (d <= n) { d *= 10; } // now add the zeros while (zeroCount > 0) { d *= 10; --zeroCount; } // d is now our true denominator result = new Double(n/(double)d); } return result; }
Example 17
Source File: NFSubstitution.java From fitnotifications with Apache License 2.0 | 4 votes |
/** * Parses a string using the rule set or DecimalFormat belonging * to this substitution. If there's a match, a mathematical * operation (the inverse of the one used in formatting) is * performed on the result of the parse and the value passed in * and returned as the result. The parse position is updated to * point to the first unmatched character in the string. * @param text The string to parse * @param parsePosition On entry, ignored, but assumed to be 0. * On exit, this is updated to point to the first unmatched * character (or 0 if the substitution didn't match) * @param baseValue A partial parse result that should be * combined with the result of this parse * @param upperBound When searching the rule set for a rule * matching the string passed in, only rules with base values * lower than this are considered * @param lenientParse If true and matching against rules fails, * the substitution will also try matching the text against * numerals using a default-constructed NumberFormat. If false, * no extra work is done. (This value is false whenever the * formatter isn't in lenient-parse mode, but is also false * under some conditions even when the formatter _is_ in * lenient-parse mode.) * @return If there's a match, this is the result of composing * baseValue with whatever was returned from matching the * characters. This will be either a Long or a Double. If there's * no match this is new Long(0) (not null), and parsePosition * is left unchanged. */ public Number doParse(String text, ParsePosition parsePosition, double baseValue, double upperBound, boolean lenientParse) { Number tempResult; // figure out the highest base value a rule can have and match // the text being parsed (this varies according to the type of // substitutions: multiplier, modulus, and numerator substitutions // restrict the search to rules with base values lower than their // own; same-value substitutions leave the upper bound wherever // it was, and the others allow any rule to match upperBound = calcUpperBound(upperBound); // use our rule set to parse the text. If that fails and // lenient parsing is enabled (this is always false if the // formatter's lenient-parsing mode is off, but it may also // be false even when the formatter's lenient-parse mode is // on), then also try parsing the text using a default- // constructed NumberFormat if (ruleSet != null) { tempResult = ruleSet.parse(text, parsePosition, upperBound); if (lenientParse && !ruleSet.isFractionSet() && parsePosition.getIndex() == 0) { tempResult = ruleSet.owner.getDecimalFormat().parse(text, parsePosition); } // ...or use our DecimalFormat to parse the text } else { tempResult = numberFormat.parse(text, parsePosition); } // if the parse was successful, we've already advanced the caller's // parse position (this is the one function that doesn't have one // of its own). Derive a parse result and return it as a Long, // if possible, or a Double if (parsePosition.getIndex() != 0) { double result = tempResult.doubleValue(); // composeRuleValue() produces a full parse result from // the partial parse result passed to this function from // the caller (this is either the owning rule's base value // or the partial result obtained from composing the // owning rule's base value with its other substitution's // parse result) and the partial parse result obtained by // matching the substitution (which will be the same value // the caller would get by parsing just this part of the // text with RuleBasedNumberFormat.parse() ). How the two // values are used to derive the full parse result depends // on the types of substitutions: For a regular rule, the // ultimate result is its multiplier substitution's result // times the rule's divisor (or the rule's base value) plus // the modulus substitution's result (which will actually // supersede part of the rule's base value). For a negative- // number rule, the result is the negative of its substitution's // result. For a fraction rule, it's the sum of its two // substitution results. For a rule in a fraction rule set, // it's the numerator substitution's result divided by // the rule's base value. Results from same-value substitutions // propagate back upward, and null substitutions don't affect // the result. result = composeRuleValue(result, baseValue); if (result == (long)result) { return Long.valueOf((long)result); } else { return new Double(result); } // if the parse was UNsuccessful, return 0 } else { return tempResult; } }
Example 18
Source File: UnitFormat.java From microMathematics with GNU General Public License v3.0 | 4 votes |
private Exponent readExponent (CharSequence csq, ParsePosition pos) { char c = csq.charAt(pos.getIndex()); if (c == '^') { pos.setIndex(pos.getIndex()+1); } else if (c == '*') { pos.setIndex(pos.getIndex()+2); } final int length = csq.length(); int pow = 0; boolean isPowNegative = false; int root = 0; boolean isRootNegative = false; boolean isRoot = false; while (pos.getIndex() < length) { c = csq.charAt(pos.getIndex()); if (c == '¹') { if (isRoot) { root = root * 10 + 1; } else { pow = pow * 10 + 1; } } else if (c == '²') { if (isRoot) { root = root * 10 + 2; } else { pow = pow * 10 + 2; } } else if (c == '³') { if (isRoot) { root = root * 10 + 3; } else { pow = pow * 10 + 3; } } else if (c == '-') { if (isRoot) { isRootNegative = true; } else { isPowNegative = true; } } else if ((c >= '0') && (c <= '9')) { if (isRoot) { root = root * 10 + (c - '0'); } else { pow = pow * 10 + (c - '0'); } } else if (c == ':') { isRoot = true; } else { break; } pos.setIndex(pos.getIndex()+1); } if (pow == 0) pow = 1; if (root == 0) root = 1; return new Exponent(isPowNegative ? -pow : pow, isRootNegative ? -root : root); }
Example 19
Source File: MessageFormat.java From fitnotifications with Apache License 2.0 | 3 votes |
/** * {@icu} Parses the string, returning the results in a Map. * This is similar to the version that returns an array * of Object. This supports both named and numbered * arguments-- if numbered, the keys in the map are the * corresponding ASCII-decimal-digit strings (e.g. "0", "1", "2"...). * * @param source the text to parse * @param pos the position at which to start parsing. on return, * contains the result of the parse. * @return a Map containing key/value pairs for each parsed argument. * @stable ICU 3.8 */ public Map<String, Object> parseToMap(String source, ParsePosition pos) { Map<String, Object> result = new HashMap<String, Object>(); int backupStartPos = pos.getIndex(); parse(0, source, pos, null, result); if (pos.getIndex() == backupStartPos) { return null; } return result; }
Example 20
Source File: DateTimeUtils.java From calcite-avatica with Apache License 2.0 | 3 votes |
/** * Parses a string using {@link SimpleDateFormat} and a given pattern. The * entire string must match the pattern specified. * * @param s string to be parsed * @param dateFormat Date format * @param tz time zone in which to interpret string. Defaults to the Java * default time zone * @return a Calendar initialized with the parsed value, or null if parsing * failed. If returned, the Calendar is configured to the UTC time zone. */ public static Calendar parseDateFormat(String s, DateFormat dateFormat, TimeZone tz) { ParsePosition pp = new ParsePosition(0); Calendar ret = parseDateFormat(s, dateFormat, tz, pp); if (pp.getIndex() != s.length()) { // Didn't consume entire string - not good return null; } return ret; }