求更好的 gsub 实现
night_stalker
2009-12-08
gsub 用法举例:
"-a-".gsub("\\w".r)(_ * 2) //=> "-aa-" "lucy: f*ck".gsub("(?=: )(.+)".r)("[此处省略%d个字]" format _.size) //=> "lucy: [此处省略4个字]" 我写的很难看而且可能效率不太好: import scala.util.matching.Regex implicit def stringX(s: String) = new Object { def gsub (re: Regex) (block: (String => String)) = { var prev = 0 val sb = new StringBuilder (re findAllIn s matchData) foreach {m => sb append (s slice (prev, m.start)) sb append block(s slice (m.start, m.end)) prev = m.end } sb append (s slice (prev, s.size)) toString } } |
|
night_stalker
2009-12-08
唔,改成了 new StringBuilder(s.size) ……
另外 slice 改成了 substring (总体来说就是少了个 if orz) …… |