Reputation: 270
I'm trying to transform a sequence like the one bellow
val raw: Seq[String] = Seq("timmy barns", "jimmy smith", "mark middle")
into a sequence that would look like this.
val parsed: Seq[(String, String)] = Seq(("timmy", "barns"), ("jimmy", "smith"), ("mark", "middle"))
The best I can come up with is something like this.
val parsed: Seq[(String, String)] = Seq(raw.map(i => i.split(" ")))
Obviously this won't work, can anyone give me suggestions?
Upvotes: 1
Views: 451
Reputation: 51271
This will gracefully, but silently, drop all input that doesn't split()
into 2 elements.
raw.map(_.split("\\s+")).collect{case Array(a,b) => (a,b)}
Upvotes: 1
Reputation: 44918
If you want to combine it with a more general regex matching anyway, this variant might be preferable:
val P = "(\\w+) +(\\w+)".r
val result = for (P(x, y) <- raw) yield (x, y)
gives:
result: Seq[(String, String)] = List((timmy,barns), (jimmy,smith), (mark,middle))
Upvotes: 1
Reputation: 309
My version )
raw.map(_.split(" ") match {
case Array(a, b) => (a, b)
})
Upvotes: 0
Reputation: 2000
May be something like this:-
val raw: Seq[String] = Seq("timmy barns", "jimmy smith", "mark middle")
val splitRaw = raw.map { x =>
(x.split(" ").head, x.split(" ").last)
}
Hope this helps!
Upvotes: 0