简体   繁体   English

在Scala中使用正则表达式的字符串格式

[英]String format using regex in Scala

I have a String in the format of "20150403" and I want to convert it into the format of string like "2015-04-03". 我有一个字符串格式为“ 20150403”,我想将其转换为字符串格式,如“ 2015-04-03”。 Is there any way using regular expression and string format in Scala? 有什么办法可以在Scala中使用正则表达式和字符串格式?

Here is a sample 这是一个样本

val date = """(\d{4})(\d{2})(\d{2})""".r
val date(year, month, day) = "20150402"
println(s"$year-$month-$day") // 2015-04-02

Regex is slow. 正则表达式很慢。 For this u need not use regex , u can use string.substring . 为此,您不需要使用正则表达式,可以使用string.substring。

val today="20150403"
val out=today.substring(0,4)+"-"+today.substring(4,6)+"-"+today.substring(6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM