Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go regexp: match three asterisks

Tags:

go

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?

like image 973
alexchenco Avatar asked Dec 12 '22 00:12

alexchenco


1 Answers

You are not checking errors.

regexp.Compile gives you two results:

  1. the compiled pattern (or nil)
  2. the error while compiling the pattern (or 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.

like image 135
nemo Avatar answered Dec 29 '22 00:12

nemo