替换为 Golang 中的正则表达式

作者:佚名

时间:2024-04-09

来源:stackoverflow

浏览:190

我使用regexp包来替换下面的文本{%macroproducts_list(products)%}{%forproductinproducts%}productslist{%endfor%}{%endmacro%}如果不替换“products_list”等其他单词,我就无法替换“products”,并且golang没有像re.replaceallstringsubmatch这样的函数来替换子匹配(只有findallstringsubmatch)。我已使

从现在开始,努力学习吧!本文《替换为 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 demo 和 regex demo。

关于模式的注释:

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

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

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

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
返回顶部