Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何使用\w+&引用;在字符串中查找单词?_Regex_Scala - Fatal编程技术网

Regex 如何使用\w+&引用;在字符串中查找单词?

Regex 如何使用\w+&引用;在字符串中查找单词?,regex,scala,Regex,Scala,我需要编写一个以字符串作为输入的函数。此函数将返回一个列表[字符串]。我必须在此函数中使用正则表达式“\w+”作为此任务的要求。因此,当给定一个随机文本行字符串,其中有一些实际单词,我需要添加所有这些“正确”单词,并将它们添加到要返回的列表中。我还必须使用“.findAllIn”。我试过以下方法 def foo(stringIn: String) : List[String] = { val regEx = """\w+""".r val match = regEx.findAl

我需要编写一个以字符串作为输入的函数。此函数将返回一个列表[字符串]。我必须在此函数中使用正则表达式“\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
的一部分。因此,它被
-

分割,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
的一部分。因此,它被
-

拆分。你能分享你的函数的完整代码吗@jat你传递的字符串是什么?foo(“hjadcahcdehellokhdbchbvsworldbhjwbff”)这是因为你的regex
\w+
匹配你的整个字符串。你能分享你的函数的完整代码吗@jatin你传递的字符串是什么?foo(“hjadcahcdehellokhdbchbvsworldkbhjwbff”),这是因为你的regex
\w+
匹配你的整个字符串。啊,好的,我明白了,糟糕的是,我是Scala的新手,并不真正理解手头的任务。谢谢大家。啊,好吧,我明白了,糟糕的是,我是Scala的新手,并没有真正理解手头的任务。谢谢大家。