>我有一个List[String],例如:
val test=List("this is, an extremely long sentence. Check; But. I want this sentence.",
"Another. extremely. long. (for eg. description). But I want this sentence.",
..)
我希望结果是这样的:
List("I want this sentence", "But I want this sentence"..)
我尝试了几种方法,但没有奏效
test.map(x=>x.split(".").reverse.head)
test.map(x=>x.split(".").最后)
尝试使用这个
test.reverse.head.split("\.").last
处理任何Exception
Try(List[String]().reverse.head.split("\.").last).getOrElse("YOUR_DEFAULT_STRING")
你可以map
你List
,split
每个String
,然后取最后一个元素。请尝试以下代码。
val list = List("this is, an extremely long sentence. Check; But. I want this sentence.",
"Another. extremely. long. (for eg. description). But I want this sentence.")
list.map(_.split("\.").last.trim)
它会给你
List(I want this sentence, But I want this sentence)
test.map (_.split("\.").last)
Split采用正则表达式,在这种情况下,点代表每个字符,因此您必须对其进行屏蔽。
也许您想包括问号和刘海:
test.map (_.split("[!?.]").last)
并修剪周围的空白:
test.map (_.split("[!?.]").last.trim).
如果没有last
,reverse.head
将是一个好主意:
scala> test.map (_.split("[!?.]").reverse.head.trim)
res138: List[String] = List(I want this sentence, But I want this sentence)
您可以通过多种方式执行此操作:
对于原始列表中的每个字符串:按.
拆分,反转列表,取第一个值
test.map(_.split('.').reverse.headOption)
// List(Some( I want this sentence), Some( But I want this sentence))
.headOption
结果是Some("string")
或None
,你可以对它做一些类似.getOrElse("no valid string found")
的事情。如果需要,您可以修剪不需要的空格。
正则表达式匹配
test.map { sentence =>
val regex = ".*\.\s*([^.]*)\.$".r
val regex(value) = sentence
value
}
这将获取较长字符串末尾的任何字符串,该字符串前面有一个句号和一个空格,后跟一个句号。您可以修改正则表达式以更改正则表达式的确切规则,如果您想学习更多正则表达式,我建议您使用 regex101.com。很好。
此解决方案更适合更复杂的示例和要求,但值得牢记。如果您担心正则表达式可能不匹配,您可以执行一些操作,例如在解压缩之前检查正则表达式是否匹配:
test.map { sentence =>
val regexString = ".*\.\s*([^.]*)\.$"
val regex = regexString.r
if(sentence.matches(regexString)) {
val regex(value) = sentence
value
} else ""
}
将字符串拆分后取最后一个.
test.map(_.split('.').map(_.trim).lastOption)