Mar*_*nkt 0 regex scala scala-2.10
我目前正在编写一个函数,使用UNIX ls -m命令列出一堆文件,然后使用正则表达式将它们转换为列表.
我的功能如下:
def genFileList(path : String = "~") : Iterator[String] = {
val fileSeparatorRegex: Regex = "(.*),".r
val fullCommand : String = s"ls -m $path"
val rawFileList: String = fullCommand.!!
val files: Iterator[String] = fileSeparatorRegex.findAllIn(rawFileList).matchData.map(_.group(1))
var debug : List[String] = files.toList
debug
files
}
Run Code Online (Sandbox Code Playgroud)
例如:假设我有一个名为test的文件夹,包含3个文件:test.txt test1.txt test2.txt.结果列表是:

很奇怪...
让我们将功能更改为:
def genFileList(path : String = "~") : Iterator[String] = {
val fileSeparatorRegex: Regex = "(.*)\\n".r \\ Changed to match newline
val fullCommand : String = s"ls -1 $path" \\ Changed to give file name separated via newline
val rawFileList: String = fullCommand.!!
val files: Iterator[String] = fileSeparatorRegex.findAllIn(rawFileList).matchData.map(_.group(1))
var debug : List[String] = files.toList
debug
files
}
Run Code Online (Sandbox Code Playgroud)
Tadaaaa:

任何人都可以帮助我理解第一个失败的案例吗?为什么生成的逗号ls -m不匹配?
(.*) 是一种贪婪的模式,它试图尽可能多地匹配,包括逗号
test1.txt, test2.txt, test3.txt
^------------------^^
all of this is |
matched by .* this is matched by ,
Run Code Online (Sandbox Code Playgroud)
最后一个块不匹配,因为它后面没有逗号.
您可以使用非贪婪匹配 .*?
或者,您可以这样做 rawFileList.stripSuffix("\n").split(", ").toList
此外,"ls -m ~".!!如果文件名包含逗号,则无法使用逗号分割输出," s"ls -m $path".!!请求shell注入,并且new File(path).list()在所有方面都更好.