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\-_]*`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法