transform string scala in an elegant way

Viewed 89

I have the following input string: val s = 19860803 000000

I want to convert it to 1986/08/03 I tried this s.split(" ").head, but this is not complete

is there any elegant scala coding way with regex to get the expected result ?

3 Answers

You can use a date like pattern using 3 capture groups, and match the following space and the 6 digits.

In the replacement use the 3 groups in the replacement with the forward slashes.

val s = "19860803 000000"
val result = s.replaceAll("^(\\d{4})(\\d{2})(\\d{2})\\h\\d{6}$", "$1/$2/$3")

Output

result: String = 1986/08/03

An alternative, without a regular expression, by using slice and take.

val s = "19860803 000000"
val year = s.take(4)
val month = s.slice(4,6)
val day = s.slice(6,8)
val result = s"$year/$month/$day"

Or as a one liner

val result = Seq(s.take(4), s.slice(4,6), s.slice(6,8)).mkString("/")
Related