实现说明
ParsePosition 严格解析以类 AmountReader为骨架。
使用要点
- 直接运行文件,输出会带上标签,比如
prefix parse:、parsed to index:、failed:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「ParsePosition 严格解析」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 prefix parse:、parsed to index:、failed: 这类标签。
核心语句
NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
NumberFormat whole = NumberFormat.getNumberInstance(Locale.US);
ParsePosition strict = new ParsePosition(0);
代码示例
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
public class AmountReader {
public static void main(String[] args) throws ParseException {
NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
// parse 只消费能解析的前缀,尾部垃圾被静默吞掉
System.out.println("prefix parse: " + de.parse("1.234,5 kg"));
// ParsePosition 重载:getIndex 告诉你消费到哪
ParsePosition pos = new ParsePosition(0);
de.parse("12,34", pos);
System.out.println("parsed to index: " + pos.getIndex());
// 失败时返回 null 并用 errorIndex 标出出错位置
ParsePosition bad = new ParsePosition(0);
Number failed = de.parse("kg,1", bad);
System.out.println("failed: " + (failed == null) + " errorIndex: " + bad.getErrorIndex());
// 尾部有剩余字符时可以显式拒绝,而不是静默接受
ParsePosition strict = new ParsePosition(0);
de.parse("12,34kg", strict);
System.out.println("leftover starts at: " + strict.getIndex() + " of 7");
// setParseIntegerOnly:解析到小数点就停
NumberFormat whole = NumberFormat.getNumberInstance(Locale.US);
whole.setParseIntegerOnly(true);
System.out.println("integer only: " + whole.parse("42.7x"));
}
}