Go中短字符串前缀匹配的更好方法:字符串或正则表达式
Better way of prefix matching in a short string in Go: strings or regexp
我知道我得到的字符串会很短(< 50 个字符)。
我也知道我的子字符串将被恰好匹配一次(或者根本不会被匹配),并且它实际上会出现在字符串的开头。
我无法决定是使用 strings.Contains
,例如 strings.Contains("123-ab-foo", "123-ab")
,还是 regexp
。我显然想要最快的方法。
用例示例:
if strings.Contains(current_string, MY_CONST){
// do smth
}
如果您确定要查找的字符串 (MY_CONST
) 将位于 current_string
的开头,那么最有效的方法将是 HasPrefix
func HasPrefix(s, prefix string) bool
HasPrefix tests whether the string s begins with prefix.
https://golang.org/pkg/strings/#HasPrefix
if strings.HasPrefix(current_string, MY_CONST){
// do smth
}
对于简单的任务,例如匹配一个精确的子字符串(尤其是前缀),字符串函数通常比正则表达式更快。
我知道我得到的字符串会很短(< 50 个字符)。 我也知道我的子字符串将被恰好匹配一次(或者根本不会被匹配),并且它实际上会出现在字符串的开头。
我无法决定是使用 strings.Contains
,例如 strings.Contains("123-ab-foo", "123-ab")
,还是 regexp
。我显然想要最快的方法。
用例示例:
if strings.Contains(current_string, MY_CONST){
// do smth
}
如果您确定要查找的字符串 (MY_CONST
) 将位于 current_string
的开头,那么最有效的方法将是 HasPrefix
func HasPrefix(s, prefix string) bool
HasPrefix tests whether the string s begins with prefix.
https://golang.org/pkg/strings/#HasPrefix
if strings.HasPrefix(current_string, MY_CONST){
// do smth
}
对于简单的任务,例如匹配一个精确的子字符串(尤其是前缀),字符串函数通常比正则表达式更快。