简体   繁体   English

如何使用“\w+”在字符串中查找单词?

[英]How to use “\w+” to find words in a string?

I need to write a function that takes a string as input.我需要编写一个将字符串作为输入的 function。 This function will return a List[String].这个 function 将返回一个 List[String]。 I have to use the regular expression "\w+" in this function as a requirement for this task.我必须在此 function 中使用正则表达式“\w+”作为此任务的要求。 So when given a line string of random text with a few actual words dotted around inside it, I need to add all of these 'proper' words and add them to the list to be returned.因此,当给定一行随机文本并在其中点缀一些实际单词时,我需要添加所有这些“正确”单词并将它们添加到要返回的列表中。 I must also use ".findAllIn".我还必须使用“.findAllIn”。 I have tried the following我试过以下

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

But it just returns the string that I pass into the function.但它只是返回我传递给 function 的字符串。

match is a reserved keyword in scala. match是 scala 中的保留关键字。 So you just need to replace that.所以你只需要替换它。

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 is the pattern for a word character, in the current regex context equal to [a-zA-Z_0-9] , that matches a lower- and uppercase letters, digits and an underscore. \\w是单词字符的模式,在当前正则表达式上下文中等于[a-zA-Z_0-9] ,它匹配大小写字母、数字和下划线。

\\w+ is for one ore more occurrences of the above. \\w+用于上述的一次或多次出现。

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

In above case, there is nothing for the regex to split by.在上述情况下,正则表达式没有什么可以分割的。 Hence returns the original string.因此返回原始字符串。

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

- is not part of \\w . -不是\\w的一部分。 Hence it splits by -因此它分为-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM