In Go, the regexp package provides several options that can modify the behavior of regular expressions. These options, or flags, can be used to control aspects such as case sensitivity, multi-line matching, and more.
(?i)): Makes the pattern case-insensitive.(?m)): Changes the behavior of ^ and $ to match the start and end of each line, not just the start and end of the string.(?s)): Changes the behavior of the dot (.) to match newline characters as well.Let's create an example where we use different regular expression options to demonstrate their effects.
package main
import (
"fmt"
"regexp"
)
func main() {
// Case Insensitivity
pattern1 := `(?i)hello`
re1, err := regexp.Compile(pattern1)
if err != nil {
fmt.Println("Error compiling regex:", err)
return
}
fmt.Println(re1.MatchString("Hello")) // Output: true
// Multi-Line Mode
pattern2 := `(?m)^hello`
re2, err := regexp.Compile(pattern2)
if err != nil {
fmt.Println("Error compiling regex:", err)
return
}
text := "hello world\\\\nHello Go\\\\nhello again"
matches := re2.FindAllString(text, -1)
fmt.Println(matches) // Output: [hello hello again]
// Dot All Mode
pattern3 := `(?s)hello.*world`
re3, err := regexp.Compile(pattern3)
if err != nil {
fmt.Println("Error compiling regex:", err)
return
}
text2 := "hello\\\\nworld"
fmt.Println(re3.MatchString(text2)) // Output: true
}
(?i)):
(?i)hello is case-insensitive.re1.MatchString("Hello") returns true because hello matches Hello regardless of case.(?m)):
(?m)^hello matches hello at the start of each line.re2.FindAllString(text, -1) finds all occurrences of hello at the start of any line in the multi-line string."hello world\\\\nHello Go\\\\nhello again" contains hello at the start of the first and third lines.["hello", "hello again"].(?s)):
(?s)hello.*world allows the dot (.) to match newline characters.re3.MatchString(text2) returns true because .* can match the newline character between hello and world."hello\\\\nworld" is matched as a whole string.(?ims)pattern enables case insensitivity, multi-line mode, and dot all mode.Here's a more practical example that combines named groups with regular expression options: