Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one occurrence with regexp

Tags:

regex

go

I want to replace a only one instance with a regex rather than all of them. How would I do this with Go's regexp library?

input: foobar1xfoobar2x
regex: bar(.)x
replacement: baz$1

ReplaceAllString output: foobaz1foobaz2
ReplaceOneString output: foobaz1foobar2x

like image 833
deft_code Avatar asked May 22 '13 23:05

deft_code


3 Answers

In general, if you use lazy match and use anchors for beginning and end, you can have the replace first behavior:

replace `^(.*?)bar(.*)$` with `$1baz$2`.

Example:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    src := "foobar1xfoobar2x"
    pat := regexp.MustCompile("^(.*?)bar(.*)$")
        repl := "${1}baz$2"
    output := pat.ReplaceAllString(src, repl)
    fmt.Println(output)
}

Output

foobaz1xfoobar2x
like image 132
perreal Avatar answered Oct 11 '22 23:10

perreal


I had the same problem. The most clean solution I've come up with:

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    re, _ := regexp.Compile("[a-z]{3}")
    s := "aaa bbb ccc"

    // Replace all strings
    fmt.Println(re.ReplaceAllString(s, "000"))

    // Replace one string
    found := re.FindString(s)
    if found != "" {
        fmt.Println(strings.Replace(s, found, "000", 1))
    }
}

Running:

$ go run test.go 
000 000 000
000 bbb ccc
like image 6
Nykakin Avatar answered Oct 11 '22 23:10

Nykakin


I cound't use accepted solution because my pattern was very complicated. I ended up with using ReplaceAllStringFunc : https://play.golang.org/p/ihtuIU-WEYG

package main

import (
    "fmt"
    "regexp"
)

var pat = regexp.MustCompile("bar(.)(x)")

func main() {
    src := "foobar1xfoobar2x"
    flag := false
    output := pat.ReplaceAllStringFunc(src, func(a string) string {
        if flag {
            return a
        }
        flag = true
        return pat.ReplaceAllString(a, "baz$1$2")
    })
    fmt.Println(output)
}
like image 3
noonex Avatar answered Oct 11 '22 21:10

noonex