Java扫描器按句子分割字符串

Java扫描器按句子分割字符串,java,regex,java.util.scanner,Java,Regex,Java.util.scanner,我正试图根据标点符号将一段文字拆分为单独的句子,即[?!]然而,扫描仪也会在每一行的末尾拆分行,即使我指定了特定的模式。我如何解决这个问题?谢谢 this is a text file. yes the deliminator works no it does not. why not? Scanner scanner = new Scanner(fileInputStream); scanner.useDelimiter("[.?!]"); while (scanner.hasNext())

我正试图根据标点符号将一段文字拆分为单独的句子,即[?!]然而,扫描仪也会在每一行的末尾拆分行,即使我指定了特定的模式。我如何解决这个问题?谢谢

this is a text file. yes the
deliminator works
no it does not. why not?

Scanner scanner = new Scanner(fileInputStream);
scanner.useDelimiter("[.?!]");
while (scanner.hasNext()) {
  line = scanner.next();
  System.out.println(line);
}

我不相信扫描器会在换行时将其拆分,只是你的“换行”变量中有换行符,这就是为什么你会得到输出。例如,可以将这些换行符替换为空格:

(我正在读取与您从文件中提供的相同的输入文本,因此它有一些额外的文件读取代码,但您将看到图片。)

结果是:

this is a text file
 yes the deliminator works no it does not
 why not
如果我取消对修剪线的注释,它会更好一些:

this is a text file
yes the deliminator works no it does not
why not

我不相信扫描器会在换行时将其拆分,只是你的“换行”变量中有换行符,这就是为什么你会得到输出。例如,可以将这些换行符替换为空格:

(我正在读取与您从文件中提供的相同的输入文本,因此它有一些额外的文件读取代码,但您将看到图片。)

结果是:

this is a text file
 yes the deliminator works no it does not
 why not
如果我取消对修剪线的注释,它会更好一些:

this is a text file
yes the deliminator works no it does not
why not

新行在您的代码中,所以它也被划界在行的末尾。从输入中删除新行。新行在代码中,因此它也在行尾被分隔。从输入中删除新行。