snippetgoCritical
How do I do a case insensitive regular expression in Go?
Viewed 0 times
howinsensitiveregularcaseexpression
Problem
I could write my regular expression to handle both cases, such as
Where
` for i := 0; i
But I feel this is a rather non-elegant solution. Speed is not really a concern, but I need to know if there is another way.
regexp.Compile("[a-zA-Z]"), but my regular expression is constructed from a string given by the user:reg, err := regexp.Compile(strings.Replace(s.Name, " ", "[ \\._-]", -1))Where
s.Name is the name. Which could be something like 'North by Northwest'. Now, the most apparent solution to me would be to walk through each character of s.Name and write '[nN]' for each letter:` for i := 0; i
But I feel this is a rather non-elegant solution. Speed is not really a concern, but I need to know if there is another way.
Solution
You can set a case-insensitive flag as the first item in the regex.
You do this by adding
For a fixed regex it would look like this.
For more information about flags, search the
(or the syntax documentation)
for the term "flags".
You do this by adding
"(?i)" to the beginning of a regex.reg, err := regexp.Compile("(?i)"+strings.Replace(s.Name, " ", "[ \\._-]", -1))For a fixed regex it would look like this.
r := regexp.MustCompile(`(?i)CaSe`)For more information about flags, search the
regexp/syntax package documentation(or the syntax documentation)
for the term "flags".
Code Snippets
reg, err := regexp.Compile("(?i)"+strings.Replace(s.Name, " ", "[ \\._-]", -1))r := regexp.MustCompile(`(?i)CaSe`)Context
Stack Overflow Q#15326421, score: 284
Revisions (0)
No revisions yet.