3

forgive me for being a regex amateur but I'm really confused as to why this doesn't piece of code doesn't work in Go

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var a string = "parameter=0xFF"
    var regex string = "^.+=\b0x[A-F][A-F]\b$"
    result,err := regexp.MatchString(regex, a)
    fmt.Println(result, err)
}
// output: false <nil>

This seems to work OK in python

import re

p = re.compile(r"^.+=\b0x[A-F][A-F]\b$")
m = p.match("parameter=0xFF")
if m is not None:
    print m.group()

// output: parameter=0xFF

All I want to do is match whether the input is in the format <anything>=0x[A-F][A-F]

Any help would be appreciated

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
djhworld
  • 6,726
  • 4
  • 30
  • 44

2 Answers2

9

Have you tried using raw string literal (with back quote instead of quote)? Like this:

var regex string = `^.+=\b0x[A-F][A-F]\b$`
antoyo
  • 11,097
  • 7
  • 51
  • 82
5

You must escape the \ in interpreted literal strings :

var regex string = "^.+=\\b0x[A-F][A-F]\\b$"

But in fact the \b (word boundaries) appear to be useless in your expression.

It works without them :

var regex string = "^.+=0x[A-F][A-F]$"

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    To be fair... I'm not sure about why it doesn't work with the `\b`. It seems it would work with a compiled regex. – Denys Séguret Jan 06 '13 at 15:58
  • 4
    `\b` is an escape character that means backspace. For instance, this code `fmt.Println("12\b3")` prints `13`. It is why you need to use the raw string literal: http://stackoverflow.com/questions/14183704/regular-expression-doesnt-work-in-go/14183804#answer-14183804 – antoyo Jan 06 '13 at 16:20
  • Ok, that explains it. More generally (when the word boundary is needed), we must escape the \ in literal strings. Thanks (and +1 on your answer). – Denys Séguret Jan 06 '13 at 16:24