{% macro products_list(products) %}
{% for product in products %}
productsList
{% endfor %}
{% endmacro %}
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 %}
But I need this result:
{% macro products_list (.) %}
{% for product in . %}
productsList
{% endfor %}
{% endmacro %}
regexgo
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
New accounts only. By submitting your email you agree to our Privacy Policy.
Heya,
The problem you’re trying to solve involves replacing only the “products” string within the parentheses, while leaving other instances of “products” untouched.
Here’s an example that might work for you. In this example, a regular expression with a lookahead and lookbehind assertion is used to target only the specific “products” string that you want to replace:
In the regular expression
(?<=products_list\()products(?=\))
:(?<=products_list\()
is a positive lookbehind that matches “products_list(” before “products”.products
is the target string to replace.(?=\))
is a positive lookahead that matches “)” after “products”.The
ReplaceAllString
method then replaces only the “products” strings that meet these conditions with “.”.Please remember that Go’s
regexp
package does not support every feature of regular expressions, and the use of lookaheads and lookbehinds is one such unsupported feature (as of my knowledge cutoff in September 2021). However, this example should help you understand the logic required to solve your problem.If you need to use advanced regular expression features in Go, you may want to consider third-party libraries that offer this functionality, such as
github.com/dlclark/regexp2
, which is a Go library that supports more features than the standardregexp
package.Finally, keep in mind that using regular expressions to parse or modify code or markup languages can be complex and error-prone due to the inherent complexity of these languages’ syntax. If you’re dealing with complex templates or if you need more flexible replacements, you might want to consider using a proper parser for the Jinja2 language.