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
}