【问题标题】:Reading text with Java Scanner next(Pattern pattern)接下来使用 Java Scanner 读取文本(模式模式)
【发布时间】:2010-10-24 22:58:57
【问题描述】:

我正在尝试使用 Scanner 类读取一行,使用 next(Pattern pattern) 方法捕获冒号之前和冒号之后的文本,以便 s1 = textbeforecolon 和 s2 = textaftercolon。

这条线看起来像这样:

某事:某事

【问题讨论】:

  • 是否必须专门使用 Pattern 对象?您可以通过正则表达式拆分字符串,而无需使用 Pattern 对象。

标签: java java.util.scanner next


【解决方案1】:

有两种方法可以做到这一点,具体取决于您想要什么。

如果你想用冒号分割整个输入,那么你可以使用useDelimiter() 方法,就像其他人指出的那样:

// You could also say "scanner.useDelimiter(Pattern.compile(":"))", but
// that's the exact same thing as saying "scanner.useDelimiter(":")".
scanner.useDelimiter(":");

// Examines each token one at a time
while (scanner.hasNext())
{
    String token = scanner.next();
    // Do something with token here...
}

如果你想用冒号分割每一行,那么使用Stringsplit()方法会容易得多:

while (scanner.hasNextLine())
{
    String[] parts = scanner.nextLine().split(":");
    // The parts array now contains ["something", "somethingelse"]
}

【讨论】:

    【解决方案2】:

    我从未将 Pattern 与扫描仪一起使用。

    我一直只是用字符串更改分隔符。 http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)

    【讨论】:

      【解决方案3】:
      File file = new File("someFileWithLinesContainingYourExampleText.txt");
      Scanner s = new Scanner(file);
      s.useDelimiter(":");
      
      while (!s.hasNextLine()) {
          while (s.hasNext()) {
              String text = s.next();
          System.out.println(text);
          }
      
          s.nextLine();
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-18
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 2014-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多