douyin6188 2017-08-20 20:59
浏览 69
已采纳

子匹配中的正则表达式替换

Given a string (a line in a log file):

Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate="12.0,18.0,24.0,36.0,48.0,54.0",host=superawesomehost.foo,foo=bar

I'd like to replace the commas with a single space, but only within double quotes.

Desired result:

Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate="12.0 18.0 24.0 36.0 48.0 54.0",host=superawesomehost.foo,foo=bar

I've begun with a basic combination of regex and ReplaceAllString but am rapidly realizing I don't understand how to implement the match group (?) needed to accomplish this.

package main

import (
    "fmt"
    "log"
    "regexp"
)

func main() {
    logLine := "Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate=\"12.0,18.0,24.0,36.0,48.0,54.0\",host=superawesomehost.foo,foo=bar"
    fmt.Println("logLine:        ", logLine)

    reg, err := regexp.Compile("[^A-Za-z0-9=\"-:]+")
        if err != nil {
                log.Fatal(err)
        }

    repairedLogLine := reg.ReplaceAllString(logLine, ",")
    fmt.Println("repairedLogLine:", repairedLogLine )   
}

All help is much appreciated.

  • 写回答

1条回答 默认 最新

  • dpo15099 2017-08-20 21:03
    关注

    You'll want to use Regexp.ReplaceAllStringFunc, which allows you to use a function result as the replacement of a substring:

    package main
    
    import (
        "fmt"
        "log"
        "regexp"
        "strings"
    )
    
    func main() {
        logLine := `Date=2017-06-29 03:10:01.140 -700 PDT,clientDataRate="12.0,18.0,24.0,36.0,48.0,54.0",host=superawesomehost.foo,foo=bar`
        fmt.Println("logLine:        ", logLine)
    
        reg, err := regexp.Compile(`"([^"]*)"`)
        if err != nil {
            log.Fatal(err)
        }
    
        repairedLogLine := reg.ReplaceAllStringFunc(logLine, func(entry string) string {
            return strings.Replace(entry, ",", " ", -1)
        })
        fmt.Println("repairedLogLine:", repairedLogLine)
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统