用Golang替换正则表达式 [英] Regex with replace in Golang

查看:1586
本文介绍了用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`)

以下是 Go demo 正则表达式



模式注释:




  • (^ | [^ _]) - 匹配字符串开始( ^ )或不是 _
  • 的字符
  • \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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆