Advertisement
Guest User

regex_replace

a guest
Mar 4th, 2014
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.19 KB | None | 0 0
  1. def measure(f: () => Unit) {
  2.     val start = System.currentTimeMillis()
  3.     f()
  4.     println(s"Elapsed: ${System.currentTimeMillis()-start}ms")
  5. }
  6.  
  7. val str = ". ? + * | { } [ ] ( ) \" \\ # @ & < > ~"
  8.  
  9. measure(() =>
  10.     for { i <- 0 to 10000000 } {
  11.         val escaped = str.replaceAll("""([\.\?\+\*\|\{\}\[\]\(\)\"\\\#\@\&\<\>\~])""", """\\\\$1""")
  12.     }
  13. )
  14.  
  15. val r = java.util.regex.Pattern.compile("""([\.\?\+\*\|\{\}\[\]\(\)\"\\\#\@\&\<\>\~])""")
  16. measure(() =>
  17.     for { i <- 0 to 10000000 } {
  18.         val escaped = r.matcher(str).replaceAll("""\\\\$1""")
  19.     }
  20. )
  21.  
  22. measure(() =>
  23.     for { i <- 0 to 10000000 } {
  24.         val escaped = escape(str)
  25.     }
  26. )
  27.  
  28. def escape(str: String): String = {
  29.     val chars = str.toCharArray()
  30.     val sb = new StringBuffer(2 * chars.length)
  31.     var i = 0
  32.     while (i < str.length) {
  33.         val c = chars(i)
  34.         (c: @scala.annotation.switch) match {
  35.             case '.' | '?' | '+' | '*' | '|' | '{' |
  36.                  '}' | '[' | ']' | '(' | ')' | '"' |
  37.                 '\\' | '#' | '@' | '&' | '<' | '>' | '~' => sb.append("""\\\\""").append(c)
  38.             case _ => sb.append(c)
  39.         }
  40.         i += 1
  41.     }
  42.     sb.toString()
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement