Nice quick way to strip a string prefix/suffix

7,067 views
Skip to first unread message

Ben Hutchison

unread,
Jun 5, 2009, 4:49:10 AM6/5/09
to Melbourne Scala User Group
Removal of a string prefix or suffix is a really common operation:

"http://mydomain" => mydomain
"sourcefile.java" => "sourcefile"

..but I cannot find any nice, quick way to do it in Scala. Can you
suggest something better than either:

val s = "string ending in suffix"

val result1 = s.substring(0, s.lastIndexOf("suffix"))

val regex="(.*)suffix".r;
regex(result2) = s; //extract from the regex

Ive asked on #scala without success. If nothing better, Im going to
raise a trac feature request for

RichString.withoutSuffix(String): String
RichString.withoutPrefix(String): String

-Ben


Ishaaq Chandy

unread,
Jun 6, 2009, 6:37:10 AM6/6/09
to scala...@googlegroups.com
You can achieve something more elegant than your two options with an implicit def and two functions to extract the suffix and prefix respectively:

class MyString(string : String) {
  def -(suffix : String) : String = {
    string.endsWith(suffix) match {
      case true => string.substring(0, string.length - suffix.length)
      case false => throw new IllegalArgumentException
    }
  }

  def -:(prefix : String) : String = {
    string.startsWith(prefix) match {
      case true => string.substring(prefix.length, string.length)
      case false => throw new IllegalArgumentException
    }
  }
}

object MyString {
  implicit def string2MyString(string : String) = new MyString(string)
}


Then, you can do something like this:

import MyString._
val string = "prefixtestsuffix"
val prefix = "prefix"
val suffix = "suffix"
println(string - suffix)//should print 'prefixtest'
println(prefix -: string) // should print 'testsuffix'

Of course, the readability of using operators as the function names is debateable, change them to ordinary function names if you prefer.

Ishaaq

2009/6/5 Ben Hutchison <brhut...@gmail.com>
Reply all
Reply to author
Forward
0 new messages