user3486527
user3486527

Reputation: 125

Golang Determine if String contains a String (with wildcards)

With Go, how would you determine if a string contains a certain string that includes wildcards? Example:

We're looking for t*e*s*t (the *'s can be any characters and any length of characters.

Input True: ttttteeeeeeeesttttttt

Input False: tset

Upvotes: 3

Views: 9869

Answers (2)

Robert Purdom
Robert Purdom

Reputation: 31

Good piece of code. I would offer one minor change. It seems to me that if you're using wildcards, then the absence of wildcards should mean exact match. To accomplish this, I use an early return....

func wildCardToRegexp(pattern string) string {
    components := strings.Split(pattern, "*")
    if len(components) == 1 {
        // if len is 1, there are no *'s, return exact match pattern
        return "^" + pattern + "$"
    }
    var result strings.Builder
    for i, literal := range components {

        // Replace * with .*
        if i > 0 {
            result.WriteString(".*")
        }

        // Quote any regular expression meta characters in the
        // literal text.
        result.WriteString(regexp.QuoteMeta(literal))
    }
    return "^" + result.String() + "$"
}

Run it on the Go Playground

Upvotes: 3

user13631587
user13631587

Reputation:

Use the regexp package by converting the * in your pattern to the .* of regular expressions.

// wildCardToRegexp converts a wildcard pattern to a regular expression pattern.
func wildCardToRegexp(pattern string) string {
    var result strings.Builder
    for i, literal := range strings.Split(pattern, "*") {

        // Replace * with .*
        if i > 0 {
            result.WriteString(".*")
        }

        // Quote any regular expression meta characters in the
        // literal text.
        result.WriteString(regexp.QuoteMeta(literal))
    }
    return result.String()
}

Use it like this:

func match(pattern string, value string) bool {
    result, _ := regexp.MatchString(wildCardToRegexp(pattern), value)
    return result
}

Run it on the Go PlayGround.

Upvotes: 6

Related Questions