([^ _] | $)
- 或者非 - _
或字符串的结尾。在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 %}
_
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:
(^|[^_])^_\bproducts\b([^_]|$)_
In the replacement pattern, we use backreferences to restore the characters captured with the parentheses (capturing groups).
这篇关于用Golang替换正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!