使用"."无法正确分割文本.分隔符

oct*_*ian 2 scala

在Scala中,我有一个由一组句子组成的文本.我试图将这个文本拆分成这样的单个句子:

val sentences: Array[String] = text.split(".")
Run Code Online (Sandbox Code Playgroud)

但是,当我检查sentences数组时(如下面的行中所示),我发现数组是空的:

println("Sentences are: " + sentences.mkString(" "))
Run Code Online (Sandbox Code Playgroud)

为什么分裂没有正确完成?

对于文字:

A sword is a bladed weapon intended for both cutting and thrusting. The precise definition of the term varies with the historical epoch or the geographical region under consideration. A sword in the most narrow sense consists of a straight blade with two edges.
Run Code Online (Sandbox Code Playgroud)

输出是:

Sentences are: 
Run Code Online (Sandbox Code Playgroud)

Tza*_*har 5

String.split需要一个正则表达式,.在正则表达式中表示"任何东西",所以你需要转义它:

val sentences: Array[String] = text.split("\\.")
Run Code Online (Sandbox Code Playgroud)

现在,如果您的分隔符是单个字符,则可以使用split(char)不会将参数解释为正则表达式的重载方法.

val sentences: Array[String] = text.split('.')
Run Code Online (Sandbox Code Playgroud)