Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a case insensitive regular expression in Go?

Tags:

regex

go

Now, of course, I could write my regular expression to handle both cases, such as 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 < len(s.Name); i++ {   if s.Name[i] == " " {     fmt.Fprintf(str, "%s[ \\._-]", str);   } else {     fmt.Fprintf(str, "%s[%s%s]", str, strings.ToLower(s.Name[i]), strings.ToUpper(s.Name[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.

like image 609
Svip Avatar asked Mar 10 '13 19:03

Svip


People also ask

Is Go Language case sensitive?

The Go Language is case sensitive.

Are regex expressions case sensitive?

By default, the comparison of an input string with any literal characters in a regular expression pattern is case-sensitive, white space in a regular expression pattern is interpreted as literal white-space characters, and capturing groups in a regular expression are named implicitly as well as explicitly.


2 Answers

You can set a case-insensitive flag as the first item in the regex.

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".

like image 194
Daniel Avatar answered Sep 28 '22 10:09

Daniel


You can add a (?i) at the beginning of the pattern to make it case insensitive.

Reference

like image 32
Qtax Avatar answered Sep 28 '22 11:09

Qtax