dongsiju1941 2018-01-26 19:27
浏览 197

使用正则表达式替换Go中的文本

I am working in Go, I have a text file in which I want to replace a text based on a regex, but it's not working as expected even when I already tested the regex here and it says that there's a match.

I made the basic example in play ground and I am getting the same result. I have 3 text files with the same label (//==start== and //==end==), it works for the first one, but no for the second and third. What can be avoiding the regex to replace correctly the text?

https://play.golang.org/p/nZdHg5IfZ89

This is the code that I used, I pasted all the string because I want to be sure that it's not the one affecting me

package main

func main() {

    var re = regexp.MustCompile(Myregex)
    s := re.ReplaceAllLiteralString(originalString,"replaced")
    fmt.Println(s)

}

var Myregex = `\/\/==start==
(.+
)*\/\/==end==`

var originalString = `// @Author: someone
// @Date:   2018-01-23T16:46:09-04:00
// @Email:  dddddddd@gmail.com
// @Filename: _material.themes.scss
// @Last modified by:   Someone
// @Last modified time: 2018-01-23T18:40:39-04:00

@include angular-material-theme($theme);

.app-dark {
    @include angular-material-theme($dark-theme);
}

.app-pink {
    @include angular-material-theme($pink-theme);
}

//==start==
//==end==`
  • 写回答

1条回答 默认 最新

  • duanpasi6287 2018-01-26 19:43
    关注

    Hope this will help you

    func main() {
        var re = regexp.MustCompile(Myregex)
        s := re.ReplaceAllString(originalString, "replaced")
        fmt.Println(s)
    }
    
    var Myregex = `//==start==
    .*
    //==end==`
    

    See in action: https://play.golang.org/p/GITAdHOOQOg

    评论

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。