Home > Mobile >  Regex Matching in golang
Regex Matching in golang

Time:10-28

How do you match the string ello w in hello world

Got to this error from trying this example

package main 

import (
    "fmt"
    "regexp"

)

func check(result string  ) string {
    
    if (regexp.MatchString("b\\ello w\\b",result)) {
        fmt.Println("Found it ")
        return "True"
    } else {
        return "False"
    }
}

func main() {
    text := "Hello world "
    check (text)
    
} 

throws the following error

# command-line-arguments
.\test.go:14:5: multiple-value regexp.MatchString() in single-value context

CodePudding user response:

regexp.MatchString returns two value. When you use it in your if conditional, compiler fails.

You should assign the return values first, then handle error case and then the match case

By the way your regex was also faulty, please see the code for a correct one for your case

https://play.golang.org/p/dNEsa9mIfhE

func check(result string  ) string {
    // faulty regex   
    // m, err := regexp.MatchString("b\\ello w\\b",result)
    m, err := regexp.MatchString("ello w",result)
    if err != nil {
      fmt.Println("your regex is faulty")
      // you should log it or throw an error 
      return err.Error()
    }
    if (m) {
        fmt.Println("Found it ")
        return "True"
    } else {
        return "False"
    }
}

func main() {
    text := "Hello world "
    check(text)
} 

CodePudding user response:

MatchString() returns 2 values, a bool and an error, so your if statement doesn't know how to process that. https://pkg.go.dev/regexp#MatchString

In the correction below, I just through away the error value but I would recommend actually checking and handling the error.

https://play.golang.org/p/awAFxxAMyWl

package main 

import (
    "fmt"
    "regexp"

)

func check(result string  ) string {
    
found, _:= regexp.MatchString(`ello w`,result)    
if (found) {
        fmt.Println("Found it ")
        return "True"
    } else {
        return "False"
    }
}

func main() {
    
    text := "Hello world "

    fmt.Println(check(text))
    
} 
  •  Tags:  
  • go
  • Related