Regex Golang中带有replace的正则表达式
我使用了regexp包来替换下面的文本Regex Golang中带有replace的正则表达式,regex,go,Regex,Go,我使用了regexp包来替换下面的文本 {% macro products_list(products) %} {% for product in products %} productsList {% endfor %} {% endmacro %} 但是我不能在不替换“产品列表”这样的词的情况下替换“产品”,而Golang没有类似于re.ReplaceAllStringSubmatch的函数来替换为submatch(只有FindAllStringSubmatch)。我使用re.Replac
{% macro products_list(products) %}
{% for product in products %}
productsList
{% endfor %}
{% endmacro %}
但是我不能在不替换“产品列表”这样的词的情况下替换“产品”,而Golang没有类似于re.ReplaceAllStringSubmatch的函数来替换为submatch(只有FindAllStringSubmatch)。我使用re.ReplaceAllString将“产品”替换为
这不是我想要的东西,我需要以下结果:
{% macro products_list (.) %}
{% for product in . %}
productsList
{% endfor %}
{% endmacro %}
您可以使用与字符串边界或非
字符(仍使用单词边界)匹配的交替捕获组:
这是一个和一个
图案说明:
(^ |[^)]
-匹配字符串开头(^
)或除
以外的字符
\b产品\b
-一个完整的词“产品”
([^]|$)
-非
或字符串结尾
在替换模式中,我们使用反向引用来恢复用括号捕获的字符(捕获组)
{% macro products_list (.) %}
{% for product in . %}
productsList
{% endfor %}
{% endmacro %}
var re = regexp.MustCompile(`(^|[^_])\bproducts\b([^_]|$)`)
s := re.ReplaceAllString(sample, `$1.$2`)