2017-10-21 27 views
1

我經歷了不同的正則表達式文件,但我仍然沒有得到它。我希望有人能夠幫助我。斯卡拉正則表達式被多個空格和新行分割

我有一個表是這樣的:

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+/等沒有工作。我非常感謝任何幫助。我的目標是將文件讀取到只有字符串和整數值的二維數組中。

回答

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) 
+1

我猜你不需要中間的.toList :) –

+0

雖然這取決於你想要對結果做什麼 - 沒有'toList','source'的類型爲'Iterator [List [String]]'特別是不會改變'source.foreach(..)'的結果,但是如果你知道你需要一個'List [List [String]]',那麼它是必需的。 –