使用Java分隔符匹配任何一个字符

时间:2012-10-14 18:18:44

标签: java character delimiter

我已经进行了搜索,但未能找到解释的示例,因此我理解或与我的确切问题相关。我正在尝试编写一个程序来取消字母A和B并读取其间的数字,例如A38484B3838。我尝试使用

    scanner.useDelimiter("[AB]");

但它不起作用。它会在它之后抛出无效输入(我正在读scanner.nextInt())。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

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

这似乎是您期望的输出。

答案 1 :(得分:0)

尝试使用正则表达式。它可以真正促进你的工作。

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]