有几种方法可以解决这个问题,但我不能保证这是最好的,但是这里是解决方案的大纲。我将离开实施作为练习,所以我不做你的功课;-)
首先,拿出一个正则表达式来贪婪地匹配数字(就像你已经有的)并且使用Java的Pattern类。
然后,使用Matcher及其replaceFirst方法用空字符串替换匹配的模式。什么结果将是一个字符串,它以第一个非数字字符开始,直到输入字符串结束。
然后,您可以通过查看“不匹配的尾部”是否为空来查看输入是否有效。
最后,如果输入无效,则使用输入字符串的索引和这个“不匹配的尾部”来告诉用户第一个坏字符在哪里。
下面是一些“剩下的练习”的轮廓。每一个“练习”都是一行一行。您应该能够在Pattern,Matcher和String的链接文档中找到所需的全部内容。
public static void main(String[] args){
String myStr = "0123f5";
//Excercise: compile a greedy number matching regex
//Excercise: get an instance of a matcher for this regex and the input string
//replace the first match in input string to greedy
//number-pattern with empty string
String mismatchedTail = m.replaceFirst("");
if(!mismatchedTail.equals("")){
System.out.println("Must enter numeric value at index: "/*Excercise: use index of, the mismatch tail, and input to get the first invalid index*/));
} else {
System.out.println("Good 2 go");
}
}
结果当我填补了空白部分运行它:
Must enter numeric value at index: 4
至少,你为什么不先写一个算法。稍后,您可以尝试编写代码。如果失败,你甚至试图找出失败的原因吗? – Pawan