dtnat7146 2019-08-01 14:57
浏览 91
已采纳

如何在Go中使用/访问捕获组? [重复]

This question already has an answer here:

I have a file with dates in the format dd.mm.yyyy (e.g. 31.12.2019). I want to transform into format yyyy-mm-dd (e.g. 2019-12-31).

In Notepad++ I can do a Search and Replace with these strings using back references:

Search:

(\d{2}).(\d{2}).(\d{4})

Replace:

\3-\2-\1

How would I do this with Go?

</div>
  • 写回答

2条回答 默认 最新

  • doudouwen2763 2019-08-01 15:03
    关注

    You could do it by slicing your input string, and assembling the parts in different order:

    func transform(s string) string {
        d, m, y := s[:2], s[3:5], s[6:]
        return y + "-" + m + "-" + d
    }
    

    Note: the above function does not validate the input, it could panic if the input is shorter than 6 bytes.

    If you need input validation (including date validation), you could use the time package to parse the date, and format it into your expected output:

    func transform2(s string) (string, error) {
        t, err := time.Parse("02.01.2006", s)
        if err != nil {
            return "", err
        }
        return t.Format("2006-01-02"), nil
    }
    

    Testing the above functions:

    fmt.Println(transform("31.12.2019"))
    fmt.Println(transform2("31.12.2019"))
    

    Output (try it on the Go Playground):

    2019-12-31
    2019-12-31 <nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!