我已经进行了搜索,但无法找到解释我理解或与我的确切问题有关的示例。我正在尝试编写一个程序来取消字母 A 和 B 并读取两者之间的数字,例如 A38484B3838。我试过使用
scanner.useDelimiter("[AB]");
但它不起作用。它抛出无效的输入(我正在阅读scanner.nextInt()
)。谁能帮忙?
public static void main(String[] args) {
String s = "A38484B3838";
Scanner scanner = new Scanner(s).useDelimiter("[AB]");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
生产
38484
3838
这似乎是您期望的输出。
尝试使用正则表达式。它确实可以促进您的工作。
public static void main(String[] args)
{
String str = "A38484B3838";
String regex = "(\d+)";
Matcher m = Pattern.compile(regex).matcher(str);
ArrayList<Integer> list = new ArrayList<Integer>();
while (m.find()) {
list.add(Integer.valueOf(m.group()));
}
System.out.println(list);
}
上述程序的输出:
[38484, 3838]