duanji4449 2018-02-23 20:23
浏览 432
已采纳

Go中短字符串中前缀匹配的更好方法:字符串或正则表达式

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 
 }
  • 写回答

1条回答 默认 最新

  • doujujian0052 2018-02-23 20:31
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色