How to correctly replace strings in golang with 'greedy principle'?

PHPz
Release: 2024-02-08 20:53:44
forward
941 people have browsed it

How to correctly replace strings in golang with greedy principle?

Question content

I tried to mask the string, but something went wrong

The reproducible code is as follows and requires all old and new pairs, how to get col1 instead of col0b?

package main

import (
    "fmt"
    "strings"
)

func main() {
    r := strings.NewReplacer("a", "col0", "ab", "col1")
    s := "ab"
    fmt.Println(r.Replace(s))
}
Copy after login

I hope that the string can be replaced using the maximum length or greedy principle


Correct answer


According to documentation, NewReplacer's replacement is as per their The strings are executed in the order they appear in the target, with no overlapping matches, so it will always follow the basis of the first match. If allowed, I think you could fix this by reorganizing the replacement pairs so that the longer string ("ab"-"col1") is placed inside the shorter string ( "a","col0")before

package main

import (
    "fmt"
    "strings"
)

func main() {
    r := strings.NewReplacer("ab", "col1", "a", "col0")
    s := "ab"
    fmt.Println(r.Replace(s))
}
Copy after login

The above is the detailed content of How to correctly replace strings in golang with 'greedy principle'?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!