Added 'flags' to the Compile function, instead of maintaining global state to check whether certain features were enabled

This commit is contained in:
2025-01-09 10:33:56 -06:00
parent 24fa365be1
commit 0b84806fc4
2 changed files with 45 additions and 16 deletions

21
main.go
View File

@@ -10,10 +10,10 @@ import (
"github.com/fatih/color"
)
var notDotChars []rune
var caseInsensitiveFlag *bool // Whether we are running in case-insensitive mode
func main() {
// Flags for the regex Compile function
flagsToCompile := make([]ReFlag, 0)
invertFlag := flag.Bool("v", false, "Invert match.")
// This flag has two 'modes':
// 1. Without '-v': Prints only matches. Prints a newline after every match.
@@ -22,17 +22,18 @@ func main() {
lineFlag := flag.Bool("l", false, "Only print lines with a match (or with no matches, if -v is enabled). Similar to grep's default.")
multiLineFlag := flag.Bool("t", false, "Multi-line mode. Treats newline just like any character.")
printMatchesFlag := flag.Bool("p", false, "Prints start and end index of each match. Can only be used with '-t' for multi-line mode.")
caseInsensitiveFlag = flag.Bool("i", false, "Case-insensitive. Disregard the case of all characters.")
caseInsensitiveFlag := flag.Bool("i", false, "Case-insensitive. Disregard the case of all characters.")
if *caseInsensitiveFlag {
flagsToCompile = append(flagsToCompile, RE_CASE_INSENSITIVE)
}
matchNum := flag.Int("m", 0, "Print the match with the given index. Eg. -m 3 prints the third match.")
substituteText := flag.String("s", "", "Substitute the contents of each match with the given string. Overrides -o and -v")
flag.Parse()
// In multi-line mode, 'dot' metacharacter also matches newline
if !(*multiLineFlag) {
notDotChars = []rune{'\n'}
} else {
notDotChars = []rune{}
if *multiLineFlag {
flagsToCompile = append(flagsToCompile, RE_MULTILINE)
}
// -l and -o are mutually exclusive: -o overrides -l
if *onlyFlag {
*lineFlag = false
@@ -74,7 +75,7 @@ func main() {
reader := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
regComp, err := Compile(re)
regComp, err := Compile(re, flagsToCompile...)
if err != nil {
fmt.Println(err)
return