Tomasz
Tomasz

Reputation: 610

use regex step by step

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.

Upvotes: 0

Views: 40

Answers (2)

jwvh
jwvh

Reputation: 51271

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

Upvotes: 3

Mario Galic
Mario Galic

Reputation: 48420

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
}

Upvotes: 2

Related Questions