From 13ca954072bf343aa8bdb5c1ca32e76625ab747d Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Thu, 19 Dec 2024 04:29:05 -0500 Subject: [PATCH] Started working on '-m num' flag : print the th match --- main.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 8e99179..53ff644 100644 --- a/main.go +++ b/main.go @@ -606,7 +606,8 @@ func main() { 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.") - substituteText := flag.String("s", "", "Substitute the contents of each match with the given string. Overrides -o and -v") + 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 @@ -619,14 +620,23 @@ func main() { if *onlyFlag { *lineFlag = false } - // Check if substitute text has been enabled + // Check if substitute and matchNum flags have been enabled substituteFlagEnabled := false + matchNumFlagEnabled := false flag.Visit(func(f *flag.Flag) { if f.Name == "s" { substituteFlagEnabled = true } + if f.Name == "m" { + matchNumFlagEnabled = true + } }) + // Validate matchNumFlag - must be positive integer + if matchNumFlagEnabled && *matchNum < 1 { + panic("Invalid match number to print.") + } + // Process: // 1. Convert regex into postfix notation (Shunting-Yard algorithm) // a. Add explicit concatenation operators to facilitate this