2013-11-15 53 views
1

我的文字,看起來像:如何在Scala中執行`sed`?

some random text yyyy-mm-dd hh:mm:ss +00:00 

什麼是將其轉換爲最簡單的方法:

some random text yyyy-mm-ddThh:mm:ss+00:00 

回答

4
val re = """(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\+00:00)""" 
val s = "some random text 1234-56-78 12:34:56 +00:00" 
s.replaceAll(re, "$1T$2$3") 
// some random text 1234-56-78T12:34:56+00:00 
2

用 「的replaceAll」 的方法:

val reg = """(\d{4}-\d{2}-\d{2}) ([0-6][0-9]:[0-6][0-9]:[0-6][0-9]) (\+\d{2}\:\d{2})""" 
"""1984-31-01 21:54:18 +00:00""".replaceAll(reg, "$1T$2$3") 

我們有> res1: String = 1984-31-01T21:54:18+00:00。 (用日期替換1984-31-01 21:54:18 +00:00)。

欲瞭解更多的相關信息:scala api

0

只是爲了好玩,遞歸格式與模式匹配。

val s = " some random text 1234-56-78 12:34:56 +00:00 some other random text 2342-34-23 12:23:43 +00:00" 

def formatString(s:String):String = { 
    val re = """(.+?)(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2})\s+(\+00:00)(.+)?""".r 
    s match { 
    case null => "" 
    case re(prefix,d,t,m,rest) => s"${prefix}${d}T${t}${m}"+formatString(rest) 
    case _ => s 
    } 
    } 

scala> formatString(s) 
res26: String = some random text 1234-56-78T12:34:56+00:00 some other random text 2342-34-23T12:23:43+00:00