Go:如何检查字符串是否包含多个子字符串?

jm3*_*_m0 5 string go

strings.Contains(str_to_check, substr)只需要一个参数作为要检查的子字符串,如何在不strings.Contains()重复使用的情况下检查多个子字符串?

例如. strings.Contains(str_to_check, substr1, substr2)

Aze*_*eem 8

您可以编写自己的实用程序函数strings.Contains(),它可以用于多个子字符串.

这是一个示例,在完成/部分匹配的情况下返回布尔值(true/ false)以及匹配的总数:

package main

import (
    "fmt"
    "strings"
)

func checkSubstrings(str string, subs ...string) (bool, int) {

    matches := 0
    isCompleteMatch := true

    fmt.Printf("String: \"%s\", Substrings: %s\n", str, subs)

    for _, sub := range subs {
        if strings.Contains(str, sub) {
            matches += 1
        } else {
            isCompleteMatch = false
        }
    }

    return isCompleteMatch, matches
}

func main() {
    isCompleteMatch1, matches1 := checkSubstrings("Hello abc, xyz, abc", "abc", "xyz")
    fmt.Printf("Test 1: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch1, matches1)

    fmt.Println()

    isCompleteMatch2, matches2 := checkSubstrings("Hello abc, abc", "abc", "xyz")
    fmt.Printf("Test 2: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch2, matches2)
}
Run Code Online (Sandbox Code Playgroud)

输出:

String: "Hello abc, xyz, abc", Substrings: [abc xyz]
Test 1: { isCompleteMatch: true, Matches: 2 }

String: "Hello abc, abc", Substrings: [abc xyz]
Test 2: { isCompleteMatch: false, Matches: 1 }
Run Code Online (Sandbox Code Playgroud)

以下是实例:https://play.golang.org/p/Xka0KfBrRD


Ale*_*nok 5

是的,您可以执行此操作而无需strings.Contains()多次调用。

如果您事先知道子字符串,那么使用正则表达式检查此字符串的最简单方法。如果要检查的字符串很长,并且您有很多子字符串,则可以更快,然后调用多个strings.Contains

示例https://play.golang.org/p/7PokxbOOo7

package main

import (
    "fmt"
    "regexp"
)

var re = regexp.MustCompile(`first|second|third`)

func main() {
    fmt.Println(re.MatchString("This is the first example"))
    fmt.Println(re.MatchString("This is the second example after first"))
    fmt.Println(re.MatchString("This is the third example"))
    fmt.Println(re.MatchString("This is the forth example"))
}
Run Code Online (Sandbox Code Playgroud)

输出:

true
true
true
false
Run Code Online (Sandbox Code Playgroud)

如果要检查的子项是动态的,则创建正则表达式可能会更加困难,因为您需要转义特殊字符,并且正则表达式编译不快,因此strings.Contains()在这种情况下可能会更好,尽管可以更好地测试代码是否对性能至关重要。

另一个不错的选择是编写自己的扫描程序,该扫描程序可以使用前缀树利用子字符串中的公共前缀(如果有)。

  • 如果它们按特定顺序排列,则可以。如果它们是任意顺序的,您仍然可以,但是对于 N > 2 ,正则表达式可能会变得非常复杂,因为您需要排列所有可能的选项 - 很快就会变得混乱。 (2认同)