dseax40600 2015-04-02 14:45
浏览 50
已采纳

为什么我的正则表达式始终在Go中失败?

I know there are plenty of questions on here asking why their regex fails, but I can't see any specifically for Go/Golang.

I have an ID type which is a string with some methods tacked on: type ID string, and this function which is supposed to return a bool if the ID is valid.

My criteria for validity are:

  • 20 characters long.
  • Any upper case letter A-Z.
  • Any digit 0-9.

So my regular expression, which I've tested on a few different online tools is /[A-Z0-9]{20}/

But every time I run my validate function it returns false, regardless of input. Specifically, the regexp.MatchString() function is returning false and nil.

Below is my validation function, match is ALWAYS false, even when I change the regex to /.{20}/ which is supposed to match 20 of anything.

func (this ID) validate() bool {

    regexString := "/[A-Z0-9]{" + strconv.Itoa(MAX_ID_LENGTH) + "}/"
    fmt.Println(regexString)

    thisStr := this.ToString()
    fmt.Println(thisStr)
    charCount := utf8.RuneCountInString(thisStr)
    fmt.Println(charCount)
    thisStr = strings.ToUpper(thisStr)
    fmt.Println(thisStr)
    match, err := regexp.MatchString(regexString, thisStr)
    fmt.Println(match, err)

    //Check string length is correct and matches regex.
    if charCount != MAX_ID_LENGTH || !match {
        return false
    } else {
        return true
    }
}

Is it to do with the way I'm using the function? I'm stumped.

Note: the .ToUpper() function is there because when my IDs are generated they are only produced with upper case letters and 0-9, but I want "abc" to be treated as "ABC" if typed manually at a later date.

  • 写回答

1条回答 默认 最新

  • duanhunlou7051 2015-04-02 14:48
    关注

    Go regular expressions should not be surrounded with / characters. Remove those and see if that works.

    The / characters are used in some languages (such as javascript and ruby) when creating regular expression literals because the \ character is used frequently in regex and requires double escaping when in a regular string. It's just a convenience in some languages, but typically is not part of the actual regex syntax (though every language handles regex a bit differently).

    The Go language does not support regex literals, but it does have the concept of string literals, which makes it much easier to write complex regular expressions.

    So, for example, to find the string \.hidden-file-009, you could write the expression as:

    "\\\\\\.[a-zA-Z0-9\\-_]*"
    

    or, more simply:

     `\\\.[a-zA-Z0-9\-_]*`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题