Question

Regex with replace in Golang

{% 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
 

Submit an answer


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!

Sign In or Sign Up to Answer

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.

KFSys
Site Moderator
Site Moderator badge
May 24, 2023

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:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    template := `{% macro products_list(products) %} {% for product in products %} productsList {% endfor %} {% endmacro %}`
    re := regexp.MustCompile(`(?<=products_list\()products(?=\))`)
    result := re.ReplaceAllString(template, ".")
    fmt.Println(result)
}

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 standard regexp 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.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel