regex - 如何使用 "\w+" 在字符串中查找单词?
问题描述
我需要编写一个将字符串作为输入的函数。此函数将返回一个 List[String]。我必须在此函数中使用正则表达式“\w+”作为此任务的要求。因此,当给定一行随机文本并在其中点缀一些实际单词时,我需要添加所有这些“正确”单词并将它们添加到要返回的列表中。我还必须使用“.findAllIn”。我试过以下
def foo(stringIn: String) : List[String] = {
val regEx = """\w+""".r
val match = regEx.findAllIn(s).toList
match
}
但它只返回我传递给函数的字符串。
解决方案
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
. 因此它分裂为-
推荐阅读
- mysql - 如何安装 mysql-server Ubuntu 18.04
- javascript - 设置 THREE.PerspectiveCamera 的距离而不改变视图方向
- python - 使用 OR 运算符合并两个数组的 ValueError
- python - 从另一个 .py 文件访问 Python 字典不会更新 Kivy 标签
- sql-server - 尝试连接到 Django 中的本地 MSSQL 数据库时,您使用什么作为主机名?
- sql - SQL 动态线索
- c++ - 在 C++ 中使用 PlaySound() 更改 BGM
- kubectl - 停止 kubectl 在最后打印“pod curl deleted”
- riscv - 命令的实现
- scala - 扩展 org.apache.spark.sql.Row 功能:Spark Scala