Search code examples
regexstringgomatchprefix

Better way of prefix matching in a short string in Go: strings or regexp


I know that the string I'll get will be short ( < 50 chars). I also know that my substring will be matched exactly once (or won't be matched at all), and that it will appear de facto at the beginning of the string.

I cannot decide whether to use strings.Contains, e.g., strings.Contains("123-ab-foo", "123-ab"), or regexp. I want the fastest way obviously.

Example of the use case:

if strings.Contains(current_string, MY_CONST){
     // do smth 
 }

Solution

  • If you are sure that the string to be found (MY_CONST) will be at the beginning of the current_string, then the most efficient way will be 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 
    }
    

    For simple tasks, like matching one exact substring (especially a prefix), string functions are generally faster than regexps.