Scala - case match partial string

后端 未结 3 1809
迷失自我
迷失自我 2021-02-01 14:50

I have the following:

serv match {

    case \"chat\" => Chat_Server ! Relay_Message(serv)
    case _ => null

}

The problem is that some

相关标签:
3条回答
  • 2021-02-01 15:18

    In case you want to dismiss any groupings when using regexes, make sure you use a sequence wildcard like _* (as per Scala's documentation).

    From the example above:

    val Pattern = "(chat.*)".r
    
    serv match {
         case Pattern(_*) => "It's a chat"
         case _ => "Something else"
    }
    
    0 讨论(0)
  • 2021-02-01 15:20

    Have the pattern matching bind to a variable and use a guard to ensure the variable begins with "chat"

    // msg is bound with the variable serv
    serv match {
      case msg if msg.startsWith("chat") => Chat_Server ! Relay_Message(msg)
      case _ => null
    }
    
    0 讨论(0)
  • 2021-02-01 15:22

    Use regexes ;)

    val Pattern = "(chat.*)".r
    
    serv match {
         case Pattern(chat) => "It's a chat"
         case _ => "Something else"
    }
    

    And with regexes you can even easily split parameter and base string:

    val Pattern = "(chat)(.*)".r
    
    serv match {
         case Pattern(chat,param) => "It's a %s with a %s".format(chat,param)
         case _ => "Something else"
    }
    
    0 讨论(0)
提交回复
热议问题