4

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
2
  • The link you've provided doesn't throw the same error. It simply prints false <nil>, Also you don't call check function from your main. Please share a reproducible example Commented Oct 27, 2021 at 19:46
  • I am learning about the regexp and i used the example in that link to write the script that throws the error Commented Oct 27, 2021 at 19:50

2 Answers 2

5

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)
} 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.