首页 > 解决方案 > 如何使用 "\w+" 在字符串中查找单词?

问题描述

我需要编写一个将字符串作为输入的函数。此函数将返回一个 List[String]。我必须在此函数中使用正则表达式“\w+”作为此任务的要求。因此,当给定一行随机文本并在其中点缀一些实际单词时,我需要添加所有这些“正确”单词并将它们添加到要返回的列表中。我还必须使用“.findAllIn”。我试过以下

def foo(stringIn: String) : List[String] = {
    val regEx = """\w+""".r
    val match = regEx.findAllIn(s).toList
    match
}

但它只返回我传递给函数的字符串。

标签: regexscala

解决方案


match是 scala 中的保留关键字。所以你只需要替换它。

def foo(stringIn: String) : List[String] = {
    val regEx = """\w+""".r
    regEx.findAllIn(stringIn).toList
}

scala> foo("hey. how are you?")
res17: List[String] = List(hey, how, are, you)

\\w是单词字符的模式,在当前正则表达式上下文中等于[a-zA-Z_0-9],它匹配大小写字母、数字和下划线。

\\w+是针对上述情况的一次或多次出现。

scala> foo("hey")
res18: List[String] = List(hey)

在上述情况下,正则表达式没有什么可以分割的。因此返回原始字符串。

scala> foo("hey-hey")
res20: List[String] = List(hey, hey)

-不属于\\w. 因此它分裂为-


推荐阅读