用Golang替换正则表达式 [英] Regex with replace in Golang
问题描述
我用regexp软件包取代了以下文本
{%macro products_list(products)%}
{%产品中的产品%}
productsList
{%endfor%}
{%endmacro%}
但我无法替换products而不替换products_list之类的词,Golang没有像 re.ReplaceAllStringSubmatch 这样的func来替代submatch只是FindAllStringSubmatch)。我用 re.ReplaceAllString 替换产品。
{%macro ._list (。)%}
{%for product in。 %}
.List
{%endfor%}
{%endmacro%}
这不是我想要的,我需要以下结果:
{%macro products_list(。)%}
{%为产品in。 %}
productsList
{%endfor%}
{%endmacro%}
var re = regexp.MustCompile(`(^ | [^ _])\bproducts\b([^ _ $ | $)`)
s:= re.ReplaceAllString(sample,`$ 1. $ 2`)
模式注释:
-
(^ | [^ _])
- 匹配字符串开始(^
)或不是_
的字符 -
\bproducts\b
- 整个单词products -
([^ _] | $)
- 或者非 -_
或字符串的结尾。
在replaceme nt模式,我们使用反向引用来恢复使用圆括号捕获的字符(捕获组)。
I've used regexp package to replace bellow text
{% macro products_list(products) %} {% for product in products %} productsList {% endfor %} {% endmacro %}
but I could not replace "products" without replace another words like "products_list" and Golang has no a func like re.ReplaceAllStringSubmatch to do replace with submatch (there's just FindAllStringSubmatch). I've used re.ReplaceAllString to replace "products" with .
{% macro ._list(.) %} {% for product in . %} .List {% endfor %} {% endmacro %}
It's not sth which I want and I need below result:
{% macro products_list (.) %} {% for product in . %} productsList {% endfor %} {% endmacro %}
解决方案You can use capturing groups with alternations matching either string boundaries or a character not
_
(still using a word boundary):var re = regexp.MustCompile(`(^|[^_])\bproducts\b([^_]|$)`) s := re.ReplaceAllString(sample, `$1.$2`)
Here is the Go demo and a regex demo.
Notes on the pattern:
(^|[^_])
- match string start (^
) or a character other than_
\bproducts\b
- a whole word "products"([^_]|$)
- either a non-_
or the end of string.
In the replacement pattern, we use backreferences to restore the characters captured with the parentheses (capturing groups).
这篇关于用Golang替换正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!