0

我目前正在编写一个函数,使用 UNIXls -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

}

例如:假设我有一个名为 test 的文件夹,其中包含 3 个文件:test.txt test1.txt test2.txt。结果列表是:

资源1

很奇怪...

让我们将函数更改为:

    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

}

太棒了:

在此处输入图像描述

任何人都可以帮助我理解第一个失败的案例吗?为什么不ls -m匹配生成的逗号?

4

2 回答 2

5

(.*)是一种贪婪模式,它会尽可能多地匹配,包括逗号

test1.txt, test2.txt, test3.txt
^------------------^^
  all of this is    |
  matched by .*     this is matched by ,

最后一个块不匹配,因为它后面没有逗号。

您可以使用非贪婪匹配.*?

或者,您可以只做rawFileList.stripSuffix("\n").split(", ").toList

此外,"ls -m ~".!!不起作用,如果文件名包含逗号,则以逗号分隔输出将不起作用,“s"ls -m $path".!!要求进行 shell 注入,并且new File(path).list()在所有方面都更好。

于 2013-11-11T23:25:44.007 回答
0

我可以看到您最初的方法存在两个问题。首先是*你的正则表达式中的 是贪婪的,这意味着它在到达逗号之前尽可能多地吸收,包括其他逗号。?如果您通过添加(ie ) 将其更改为非贪婪,"(.*?),".r它将仅匹配第一个逗号。

第二个问题是最后一个文件后面没有逗号(自然),因此正则表达式不会找到它。在您的第二种方法中,您将获得所有三个文件,因为每个文件后面都有一个换行符。如果您想坚持使用逗号,最好使用split(例如rawFileList.split(","))。

您也可以考虑在 上使用listorlistFiles方法java.io.File

scala> val dir = new java.io.File(".")
f: java.io.File = .

scala> dir.list
res0: Array[String] = Array(test, test1.txt, test2.txt)
于 2013-11-11T23:46:16.467 回答