Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Regex in golang function

Tags:

go

I want to pass a compiled regex to golang function, e.g.

package main

import "fmt"
import "regexp"

func foo(r *Regexp) {
    fmt.Println(r)    
}

func main() {

    r, _ := regexp.Compile("p([a-z]+)ch")
    foo(r)
}

But it is showing "undefined: Regexp"

Any hints?

like image 519
Howard Avatar asked May 01 '14 10:05

Howard


1 Answers

Use a qualified identifier. For example,

package main

import "fmt"
import "regexp"

func foo(r *regexp.Regexp) {
    fmt.Println(r)
}

func main() {

    r, _ := regexp.Compile("p([a-z]+)ch")
    foo(r)
}

Output:

p([a-z]+)ch

Qualified identifiers

A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not be blank.

QualifiedIdent = PackageName "." identifier .

A qualified identifier accesses an identifier in a different package, which must be imported. The identifier must be exported and declared in the package block of that package.

math.Sin  // denotes the Sin function in package math
like image 184
peterSO Avatar answered Sep 20 '22 23:09

peterSO