Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Matching in golang

Tags:

go

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
like image 877
max.syntax Avatar asked Oct 30 '25 17:10

max.syntax


1 Answers

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)
} 
like image 168
Alper Avatar answered Nov 01 '25 13:11

Alper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!