A question about string matching

Hi all,

Is there an easier way to check the string as below?

Many thanks,
X. YANG

def checkString(s: String): String = {
require((s != null) && (s startsWith "hello:"))

if (s startsWith "hello:tom") return "Hello Tom"
else if (s startsWith "hello:jerry") return "Hello Jerry"

"Who are you?"
}

Re: A question about string matching

def checkString(s: String) = "^hello:(.*)".r.unapplySeq(s) match {
  case Some(List(name)) => name match {
    case "tom" => "Hello Tom"
    case "jerry" => "Hello Jerry"
    case _ => "Who are you?"
  }
  case _ => throw new IllegalArgumentException("String did not start with hello:")
}

The regex "^hello:(.*)".r matches a string starting with hello: and captures the following text.  We then match on it, but if successful it returns a List(Some(the_matched_string)), which is a bit awkward to keep writing down, so we match on the contents which is just the name (if any).

If you really have to catch the null string, then you should put that require first.

  --Rex

On Fri, Feb 26, 2010 at 5:55 AM, Xiaobo Yang <xiaobo [dot] yang [at] gmail [dot] com> wrote:
Hi all,

Is there an easier way to check the string as below?

Many thanks,
X. YANG

       def checkString(s: String): String = {
               require((s != null) && (s startsWith "hello:"))

               if (s startsWith "hello:tom") return "Hello Tom"
               else if (s startsWith "hello:jerry") return "Hello Jerry"

               "Who are you?"
       }

Re: A question about string matching

Extractors are your friend here, then you can use pattern matching:
object HelloStr { def unapply(s : String): Option[String] = if (s startsWith "hello:") Some(s substring 6) else None}
def checkString(s: String) : String = s match {
case HelloStr(s) if s startsWith "tom" => "Hello Tom" case HelloStr(s) if s startsWith "jerry" => "Hello Jerry" case HelloStr(_) => "Who are you?" case _ => error("String doesn't start with hello:") }



This would also be a good one to ask on stack Overflow

On 26 February 2010 10:55, Xiaobo Yang <xiaobo [dot] yang [at] gmail [dot] com> wrote:
Hi all,

Is there an easier way to check the string as below?

Many thanks,
X. YANG

       def checkString(s: String): String = {
               require((s != null) && (s startsWith "hello:"))

               if (s startsWith "hello:tom") return "Hello Tom"
               else if (s startsWith "hello:jerry") return "Hello Jerry"

               "Who are you?"
       }



--
Kevin Wright

mail/google talk: kev [dot] lee [dot] wright [at] googlemail [dot] com
wave: kev [dot] lee [dot] wright [at] googlewave [dot] com
skype: kev.lee.wright
twitter: @thecoda

Copyright © 2013 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland