max.syntax
max.syntax

Reputation: 83

Regex Matching in golang

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

Upvotes: 4

Views: 14824

Answers (2)

Cadet
Cadet

Reputation: 354

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))
    
} 

Upvotes: 1

Alper
Alper

Reputation: 601

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)
} 

Upvotes: 4

Related Questions