0

For example, in this sentence,

Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania. Let freedom ring from the snow-capped Rockies of Colorado. Let freedom ring from the curvaceous slopes of California.

how to replace "Let freedom" with

"[1] Let freedom", "[2] Let freedom2", and so on.

I searched the Go regexp package, failed to find anything related increase counter. (Only find the ReplaceAllStringFunc, but I don't know how to use it.)

2 Answers 2

2

You need something like this

r, i := regexp.MustCompile("Let freedom"), 0
r.ReplaceAllStringFunc(input, func(m string) string {
   i += 1
   if i == 1 {
     return "[1]" + m 
   }
   return fmt.Sprintf("[%d] %s%d", i, m, i)
})

Make sure you've imported required packages.. The above works by using Let freedom as the regex and then using some conditions to return what is intended.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to somehow share counter between successive calls to your function. One way to do this is to construct closure. You can do it this way:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str := "Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania. Let freedom ring from the snow-capped Rockies of Colorado. Let freedom ring from the curvaceous slopes of California."
    counter := 1
    repl := func(match string) string {
        old := counter
        counter++
        if old != 1 {
            return fmt.Sprintf("[%d] %s%d", old, match, old)
        }
        return fmt.Sprintf("[%d] %s", old, match)
    }
    re := regexp.MustCompile("Let freedom")
    str2 := re.ReplaceAllStringFunc(str, repl)
    fmt.Println(str2)
}

1 Comment

Thank you very much! +1 for your explanation on construct closure. Your code works well. I don't understand the if old != 1 { return fmt.Sprintf("[%d] %s%d", old, match, old) } part. So I removed it, the code still works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.