File: t0325.scala

package info (click to toggle)
scala 2.11.12-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 62,924 kB
  • sloc: javascript: 28,808; java: 13,415; xml: 3,135; sh: 1,620; python: 756; makefile: 38; awk: 36; ansic: 6
file content (53 lines) | stat: -rw-r--r-- 1,407 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
case class RS(self: String) {

  // NB. "\\Q" + '\\' + "\\E" works on Java 1.5 and newer, but not on Java 1.4
  private def escape(ch: Char): String = ch match {
    case '\\' => "\\\\"
    case _ => "\\Q"+ch+"\\E"
  }

  def split(separator: Char): Array[String] = self.split(escape(separator))

  def split(separators: Array[Char]): Array[String] = {
    val re = separators.foldLeft("[")(_+escape(_)) + "]"
    self.split(re)
  }
}

object Test {
  def expect = List("a","b")
  def test(f: => Array[String], which: String) {
    try {
      val ret = f.toList
      if (ret != expect)
        println(which + " returned " + ret + " when expecting " + expect)
      else
        println(ret)
    } catch {
      case e: Throwable => println(which + " failed with " + e.getClass)
    }
  }

  def main(args: Array[String]) {
    val badChars = "?*{+([\\^.$"

    for (c <- badChars)
      test(("a"+c+"b").split(c),"RichString split('"+ c + "')")
    println

    for (c <- badChars)
      test(RS("a"+c+"b").split(c),"RS split('"+ c + "')")
    println

    val badCases = List(
      ']' -> "x]", '&' -> "&&",'\\' -> "\\x", '[' -> "[x",
      '^' -> "^x", '-' -> "x-z"
    )
    for ((c,str) <- badCases)
      test(("a"+c+"b").split(str.toArray),"RichString split(\""+ str + "\")")
    println

    for ((c,str) <- badCases)
      test(RS("a"+c+"b").split(str.toArray),"RS split(\""+ str + "\")")
  }
}