登录
首页 >  Golang >  Go问答

替换为 Golang 中的正则表达式

来源:stackoverflow

时间:2024-04-09 10:33:32 190浏览 收藏

从现在开始,努力学习吧!本文《替换为 Golang 中的正则表达式》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我使用 regexp 包来替换下面的文本

{% macro products_list(products) %}
{% for product in products %}
productslist
{% endfor %}
{% endmacro %}

如果不替换“products_list”等其他单词,我就无法替换“products”,并且 golang 没有像 re.replaceallstringsubmatch 这样的函数来替换子匹配(只有 findallstringsubmatch)。我已使用 re.replaceallstring 将“产品”替换为 。

{% macro ._list(.) %}
{% for product in . %}
.list
{% endfor %}
{% endmacro %}

但我需要这个结果:

{% macro products_list (.) %}
{% for product in . %}
productsList
{% endfor %}
{% endmacro %}

正确答案


您可以使用捕获组,其交替匹配字符串边界或非 _ 的字符(仍使用单词边界):

var re = regexp.MustCompile(`(^|[^_])\bproducts\b([^_]|$)`)
s := re.ReplaceAllString(sample, `$1.$2`)

这是 Go demoregex demo

关于模式的注释:

  • (^|[^_]) - 匹配字符串开头 (^) 或 _ 以外的字符
  • \bproducts\b - 整个单词“产品”
  • ([^_]|$) - 非 _ 或字符串结尾。

在替换模式中,我们使用反向引用来恢复用括号捕获的字符(捕获组)。

好了,本文到此结束,带大家了解了《替换为 Golang 中的正则表达式》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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