【问题标题】:Scala regex split by multiple spaces and new lineScala 正则表达式被多个空格和换行符分割
【发布时间】:2017-10-21 04:28:37
【问题描述】:

我为此浏览了不同的正则表达式文档,但我仍然没有得到它。我希望有人能够帮助我。

我有一张这样的桌子:

program     1  0  1  1  0  0  0  0  0  0  0  1
stmt_list   2  0  2  2  0  0  0  0  0  0  0  3
stmt        4  0  5  6  0  0  0  0  0  0  0  0

我想从文件中读取它并存储在一个数组中。我做了以下事情:

val source = io.Source.fromFile("file.txt").getLines.toList.mkString.split("\\W+")

我得到如下输出:

program
1
0
1
1
0
0
0
0
0
0
0
1stmt_list // this is problem, int and string together which I don't want.
2
0
2
2
0
0
0
0
0
0
0
3stmt
4
0
.
.
.

我了解到\s 匹配任何空格、制表符或换行符。但是当我尝试时,我在 scala error: invalid escape character 上遇到错误。我尝试了许多其他步骤:" +"/\W+/ 等。没有一个有效。我将非常感谢任何帮助。我的目标是将文件读入一个只有字符串和整数值的二维数组。

【问题讨论】:

    标签: regex scala split io


    【解决方案1】:

    您的问题不在于正则表达式本身,而是您将所有行“合并”为一个字符串(使用mkString)而不是使用map 分别对每一行进行操作:

    val source = Source.fromFile("file.txt")
      .getLines.toList             // gets a list of file lines
      .map(_.split("\\W+").toList) // maps each line into a list
    
    source.foreach(println)
    // List(program, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1)
    // List(stmt_list, 2, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 3)
    // List(stmt, 4, 0, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0)
    

    【讨论】:

    • 我猜你不需要中间的 .toList :)
    • 是的,尽管这取决于您要对该结果做什么 - 没有 toListsource 的类型为 Iterator[List[String]] - 适用于大多数用途,特别不会改变结果source.foreach(..),但如果您知道需要 List[List[String]],则需要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    相关资源
    最近更新 更多