Golang 使用正则来匹配出子字符串函数
Posted 禅与计算机程序设计艺术
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang 使用正则来匹配出子字符串函数相关的知识,希望对你有一定的参考价值。
const SERVICE_IMPL_RULE = ".*?\\\\.NewServer\\\\(new\\\\((.*?)\\\\)\\\\)"
// getServiceImpl 返回: CompassInsightServiceImpl
// .ServiceImpl = CompassInsightServiceImpl
// svr := insight_service.NewServer(new(CompassInsightServiceImpl))
func getServiceImpl(filePath string) string
f, err := os.Open(filePath)
if err != nil
return ""
buf := bufio.NewReader(f)
for
line, err := buf.ReadString('\\n')
line = strings.TrimSpace(line)
if strings.Contains(line, ".NewServer(new(")
byRegex, err := GetOneStringByRegex(line, SERVICE_IMPL_RULE)
if err != nil
log.Error(err)
return ""
return byRegex
if err != nil
if err == io.EOF
return ""
return ""
const SVR_RULE = "svr := (.*?)\\\\.NewServer\\\\(new\\\\(.*?\\\\)\\\\)"
// getNewServerCodeLine 返回: insight_service
// originLine = svr := insight_service.NewServer(new(CompassInsightServiceImpl))
// .NewServerCodeLine = insight_service
//svr := .NewServerCodeLine .NewServer( .ServiceImpl , server.WithMiddleware(transform.ServerTransform), server.WithMiddleware(logmv.ServerLog))
//svr := insight_service.NewServer( CompassInsightServiceImpl, server.WithMiddleware(transform.ServerTransform), server.WithMiddleware(logmv.ServerLog))
func getNewServerCodeLine(filePath string) string
f, err := os.Open(filePath)
if err != nil
return ""
buf := bufio.NewReader(f)
for
line, err := buf.ReadString('\\n')
line = strings.TrimSpace(line)
if strings.Contains(line, ".NewServer(new(")
byRegex, err := GetOneStringByRegex(line, SVR_RULE)
if err != nil
log.Error(err)
return ""
return byRegex
if err != nil
if err == io.EOF
return ""
return ""
// GetOneStringByRegex 使用正则来匹配出子字符串函数:
//使用案例:
//从 img[/static/upload/xxxx/xxx.jpg] 中获取 xxxx/xxx.jpg
//url, _ = GetOneStringByRegex(str, "img\\\\[.*?/static/upload/(.*?)\\\\]")
func GetOneStringByRegex(str, rule string) (string, error)
reg, err := regexp.Compile(rule)
if reg == nil || err != nil
return "", errors.New("正则Compile错误:" + err.Error())
//提取关键信息
result := reg.FindStringSubmatch(str)
if len(result) < 1
return "", errors.New("没有获取到子字符串")
return result[1], nil
以上是关于Golang 使用正则来匹配出子字符串函数的主要内容,如果未能解决你的问题,请参考以下文章