Reputation: 843
I have done a search but have not been able to find an example that explained so I understood or that pertained to my exact question. I am trying to write a program that cancels out the letters A and B and reads the numbers inbetween, such as A38484B3838. I tried using
scanner.useDelimiter("[AB]");
but it doesnt work. It throws invalid input (I'm reading scanner.nextInt()
) after it. can anyone help?
Upvotes: 0
Views: 750
Reputation: 25950
Try using regular expressions. It could really facilitate your work.
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);
}
Output of the program above:
[38484, 3838]
Upvotes: 0
Reputation: 1076
public static void main(String[] args) {
String s = "A38484B3838";
Scanner scanner = new Scanner(s).useDelimiter("[AB]");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
produces
38484
3838
It seems like the output you'd expect.
Upvotes: 3