0

I would like to 'decompose' a longer string into smaller Strings and store results in a separate variables. I mean:

// my string to split
val fileName: String = '15_data_doc1-financial-aspects_20190105_101000_c_from-another-department.csv

// split into smaller variables...
val number = 15
val type   = "data"
val doc    = "doc1"
...

Would be great to do it step by step, like: 1) apply some regex on the string and save the result into new variable 2) save a tail of the String and apply further regex logic to create next variable.

Which solution would be the most convinient to achieve the goal? Pattern matching with, tail recursion, just creating a subsidiary variable after each operation? Normally, I would use 'split' method, but in this situation there are few characters for splitin purpose.

Any advice welcome.

Tomasz
  • 610
  • 4
  • 22

2 Answers2

3

If you can't use interpolated string patterns (Scala 2.13.0), you could build a regex to describe the decomposition pattern.

val fileName: String =
    "15_data_doc1-financial-aspects_20190105_101000_c_from-another-department.csv"

val FNPattern = "([^_]+)_([^_]+)_([^-]+)-([^.]+)\\.(.+)".r

fileName match {
  case FNPattern(number, tpe, doc, rest, ext) => s"$number, $tpe, $doc, $ext"
}
//res0: String = 15, data, doc1, csv
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Could you explain the meaning of "\\.(.+)", please? – Tomasz Sep 05 '19 at 09:32
  • `\\.` = literal (escaped) dot (not the wildcard character), `(.+)` = a string of one or more characters, considered as a (group). – jwvh Sep 05 '19 at 09:42
2

Try interpolated string patterns as suggested by Krzysztof Atłasik

"15_data_doc1-financial-aspects_20190105_101000_c_from-another-department.csv" match {
  case s"${number}_${filetype}_${doc}" => // use number, filetype, doc, etc. variables
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • Thanks Mario! Apologize, but i din't mention, that use Scala 2.10. Looks interpolated string patterns are being supported after Scala 2.13. – Tomasz Sep 05 '19 at 08:35