Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex "is not a constant" compilation error

Tags:

regex

go

I'm trying to write a regex in Go to verify that a string only has alphanumerics, periods, and underscores. However, I'm running into an error that I haven't seen before and have been unsuccessful at Googling.

Here's the regex:

pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)

Here is the error:

const initializer regexp.MustCompile("^[A-Za-z0-9_\\.]+") is not a constant

What does "not a constant" mean and how do I fix this?

like image 347
joulesm Avatar asked Jun 22 '16 18:06

joulesm


2 Answers

This happens when you're trying to assign to a constant that has a type that can't be constant (like for example, Regexp). Only basic types likes int, string, etc. can be constant. See here for more details.

Example:

pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
// which translates to:
const pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)

You have to declare it as a var for it to work:

var pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)

In addition, I usually put a note to say that the variable is treated as a constant:

var /* const */ pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)
like image 108
robbrit Avatar answered Nov 14 '22 03:11

robbrit


The error is pretty clear. If you are trying to do this globally...

Don't do:

const pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)

Instead do:

var pattern = regexp.MustCompile(`^[A-Za-z0-9_\.]+`)

Or if you really want the pattern in a constant:

const pattern = `^[A-Za-z0-9_\.]+`
var alphaNum = regexp.MustCompile(pattern)
like image 10
eduncan911 Avatar answered Nov 14 '22 04:11

eduncan911