在Golang中使用替换的正则表达式

时间:2016-05-17 11:03:25

标签: regex go

我已使用regexp软件包替换以下文字

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

但我无法取代"产品"没有替换像" products_list"并且Golang没有像 re.ReplaceAllStringSubmatch 这样的函数来替换submatch(只有FindAllStringSubmatch)。我已经使用 re.ReplaceAllString 来替换"产品"与。

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

这不是我想要的,我需要以下结果:

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

1 个答案:

答案 0 :(得分:41)

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).