So I did this:
r, _ := regexp.Compile("* * *")
r2 := r.ReplaceAll(b, []byte("<hr>"))
and got:
panic: runtime error: invalid memory address or nil pointer dereference
So I figured I had to escape them:
r, _ := regexp.Compile("\* \* \*")
But got unknown escape secuence
I'm a Go Beginner. What am I doing wrong?
Adding to @VonC's answer, regexp aren't always the answer and are generally slower than using strings.*
.
For a complex expression, sure regexp is awesome, however if you just want to match a string and replace it then, strings.Replacer
is the way to go:
var asterisksReplacer = strings.NewReplacer(`* * *`, `<hr>`)
func main() {
fmt.Println(asterisksReplacer.Replace(`xxx * * * yyy *-*-* zzz* * *`))
}
Try escaping your '*
' (since '*
' is a special character used for repetition in the re2 syntax)
r, err := regexp.Compile(`\* \* \*`)
// and yes, always check the error
// or at least use regexp.MustCompile() if you want to fail fast
Note the use of back quotes `` for the string literal.
You are not checking errors.
regexp.Compile
gives you two results:
nil
)nil
)You are ignoring the error and accessing the nil
result. Observe (on play):
r, err := regexp.Compile("* * *")
fmt.Println("r:", r)
fmt.Println("err:", err)
Running this code will show you that, indeed there is an error. The error is:
error parsing regexp: missing argument to repetition operator:
*
So yes, you are right, you have to escape the repetition operator *
. You tried the following:
r, err := regexp.Compile("\* \* \*")
And consequently you got the following error from the compiler:
unknown escape sequence: *
Since there are a number of escape sequences like or
for special characters that you do not have on your keyboard but want to have in strings, the compiler tries to insert these characters.
\*
is not a valid escape sequence and thus the compiler fails to do the replacement. What you want to do is to escape the escape sequence so that the regexp parser can do its thing.
So, the correct code is:
r, err := regexp.Compile("\\* \\* \\*")
The simplest way of dealing with these kind of quirks is using the raw string literals ("``") instead of normal quotes:
r, err := regexp.Compile(`\* \* \*`)
These raw strings ignore escape sequences altogether.