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?
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 \n
or \r
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With