登录
首页 >  Golang >  Go问答

使用正则表达式在 Go 中替换字符串和字符串数组时不考虑大小写

来源:stackoverflow

时间:2024-02-18 18:06:21 238浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《使用正则表达式在 Go 中替换字符串和字符串数组时不考虑大小写》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

我遇到过这样的情况,我需要对 go (json) 字符串中的字符串进行不区分大小写的替换。替换可以是以下几种情况

  1. 搜索字符串:some_search_string;替换字符串 replacment_string
  2. 搜索字符串:"[\"some_search_string\"]";替换字符串 "[\"intv2rpacs\"]"

我的正则表达式如下

pattern := fmt.Sprintf(`(%s)`, searchString)
pat := regexp.MustCompile("(?i)" + pattern)
content = pat.ReplaceAllString(content, replacementString)

当搜索和替换字符串值是简单字符串时,上面的方法似乎工作正常,但当搜索是替换值数组时(例如上面的#2),上面的方法就会失败。我需要做什么正则表达式更新才能替换数组?


正确答案


使用 regexp.QuoteMeta 引用搜索字符串中的元字符。

pattern := fmt.sprintf(`(%s)`, regexp.quotemeta(searchstring))
pat := regexp.mustcompile("(?i)" + pattern)
content = pat.replaceallstring(content, replacementstring)
package main

import (
    "fmt"
    "regexp"
)

type rep struct {
    from string
    to   string
}

func replace(str string, reps []rep) (result string) {
    result = str

    for i := range reps {
        rx := regexp.mustcompile(fmt.sprintf("(?i)(%s)", regexp.quotemeta(reps[i].from)))
        result = rx.replaceallstring(result, reps[i].to)
    }
    return
}

func main() {
    content := `
{
    "key_1": "some_search_string",
    "key_2": "some_some_search_string_string",
    "key_3": ["some_search_string"],
    "key_4": "abc"
}`

    var replaces = []rep{
        {`["some_search_string"]`, `["intv2rpacs"]`},// important: array replacements before strings
        {`some_search_string`, `replacement_string`},
    }

    fmt.println(content)
    fmt.println(replace(content, replaces))
}
output:

{
    "key_1": "SoME_SEArCH_STRING",
    "key_2": "some_some_SEARCH_STRING_string",
    "key_3": ["SOME_SEARCH_STRING"],
    "key_4": "aBc"
}

{
    "key_1": "REPLACEMENT_STRING",
    "key_2": "some_REPLACEMENT_STRING_string",
    "key_3": ["INTv2RPACS"],
    "key_4": "aBc"
}

理论要掌握,实操不能落!以上关于《使用正则表达式在 Go 中替换字符串和字符串数组时不考虑大小写》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>