Reputation: 297
I have a file as below,
AB*xyz*1234~
CD*mny*769~
MN*bvd*2345~
AB*zar*987~
here i would like to split the data using(*) and line always ends with ~.
code.
val bufferedSource = Source.fromFile(sample.txt)
var array = Array[String]()
for (line <- bufferedSource.getLines()) {
array = line.split("\\~")
val splittedRow=array.split("\\*")
}
I want output as below which should be first words from all lined,
Array(AB,CD,MN,AB).
Upvotes: 0
Views: 477
Reputation: 1568
You can also use collect
to get what you want
val s = Source.fromFile("fileName").getLines().collect{
case e => e.split("\\*").apply(0)
}.toArray
//s: Array[String] = Array(AB, CD, MN, AB)
Upvotes: 0
Reputation: 22125
This is probably better achieved by mapping over the lines from the file, and selecting the part of the string you want to keep:
val array =
Source.fromFile(sample.txt) // Open the file
.getLines() // get each line
.toArray // as an array
.map(s => s.split("\\*").head) // Then select just the first part
// of the line, split by * characters
Upvotes: 1
Reputation: 41957
You can simply do
Source.fromFile(filename).getLines().map(line => line.split("\\*").head).toArray
//res0: Array[String] = Array(AB, CD, MN, AB)
Upvotes: 1