switch(string) - pattern matching?

14,108 views
Skip to first unread message

Vincent Ambo

unread,
Aug 18, 2011, 8:35:06 AM8/18/11
to golang-nuts
Hej,

If I use a switch statement on a string var, is it possible to get cases by pattern matching? (regex or formatstrings)

For example:
var s string
switch(s) {
case "%02d.%04d":

etc.

I'm not on a computer where I can test this at the moment but I'm trying to get some code done anyways. Help much appreciated!

Thanks in advance,
Vincent

Skickat från min iPhone

Olivier Gagnon

unread,
Aug 18, 2011, 8:50:15 AM8/18/11
to golan...@googlegroups.com
You can try code in the sandbox on the main page of http://golang.org/.

Andy Balholm

unread,
Aug 18, 2011, 12:27:21 PM8/18/11
to golan...@googlegroups.com
No, switch only works with exact equality, not with pattern match.

But you could use a boolean switch:

package main

import (
"fmt"
"regexp"
)

var twoPointFour = regexp.MustCompile(`^[0-9][0-9]\.[0-9][0-9][0-9][0-9]$`)
var twoPointTwo = regexp.MustCompile(`^[0-9][0-9]\.[0-9][0-9]$`)

func main() {
s := "12.3456"
switch {
case twoPointFour.MatchString(s):
fmt.Println("2.4")
case twoPointTwo.MatchString(s):
fmt.Println("2.2")
default:
fmt.Println("It doesn't match")
}
}

Andy

Kyle Lemons

unread,
Aug 18, 2011, 12:36:26 PM8/18/11
to Vincent Ambo, golang-nuts
You can use switch{} (the short form of switch true {}) to achieve a similar effect:


var email = regexp.MustCompile(`^[^@]+@[^@.]+\.[^@.]+`)
var shortPhone = regexp.MustCompile(`^[0-9][0-9][0-9][.\-]?[0-9][0-9][0-9][0-9]`)
var longPhone = regexp.MustCompile(`^[(]?[0-9][0-9][0-9][). \-]*[0-9][0-9][0-9][.\-]?[0-9][0-9][0-9][0-9]`)
// ...
switch {
case email.MatchString(contact):
  fmt.Println(contact, "is an email")
case shortPhone.MatchString(contact):
  fmt.Println(contact, "is a short phone number")
case longPhone.MatchString(contact):
  fmt.Println(contact, "is a long phone number")
default:
  fmt.Println(contact, "is not recognized")
}
Reply all
Reply to author
Forward
0 new messages