Golang正则表达式 与 strings 结合获取文件信息

package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
)

func main() {
	path := `.\info\1239875_low.txt`
	GetMaxInfo(path)
}

func GetMaxInfo(path string)  {
	//path := `.\info\1239875_low.txt`
	//fmt.Println(os.Getwd())
	//fmt.Println(filepath.Abs(path))

	//获取贴图
	//读取文件,返回整个内容
	//正则获取取想要的内容
	contentsByte, _ := ioutil.ReadFile(path)
	contentString := string(contentsByte)

	regMap := regexp.MustCompile("(?s:External Dependencies(.*?)Materials)")
	resultMap := regMap.FindAllStringSubmatch(contentString, -1)[0][1]
	maps := H_GetListFromString(resultMap)
	fmt.Println(maps)
	regMat := regexp.MustCompile("(?s:Materials(.*))")
	resultMat := regMat.FindAllStringSubmatch(contentString,-1)[0][1]
	mats := H_GetListFromString(resultMat)
	fmt.Println(mats)

	//打开文件
	//声明bufio.Reader
	//读取文件

	rw, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer rw.Close()

	rb := bufio.NewReader(rw)
	getMaxInfoFromContents(rb)
}
func getMaxInfoFromContents(rb *bufio.Reader) {
	//获取其它字段
	for {
		line, _, err := rb.ReadLine()
		if err == io.EOF {
			break
		}
		lineinfo := strings.TrimSpace(string(line))

		switch {
		case strings.HasPrefix(lineinfo, "Identifier:{"):
			//do somethin
			fmt.Println(lineinfo)

		case strings.HasPrefix(lineinfo, "Created:"):
			fmt.Println(lineinfo)

		case strings.HasPrefix(lineinfo, "Modified:"):
			fmt.Println(lineinfo)

		case strings.Contains(lineinfo, "Compressed"):
			fmt.Println(lineinfo)

		case strings.HasPrefix(lineinfo, "Vertices:"):
			fmt.Println(lineinfo)

		case strings.HasPrefix(lineinfo, "Faces:"):
			fmt.Println(lineinfo)

		case strings.HasPrefix(lineinfo, "Objects:"):
			fmt.Println(lineinfo)
		case strings.HasPrefix(lineinfo, "Lights:"):
			fmt.Println(lineinfo)
		case strings.HasPrefix(lineinfo, "Cameras:"):
			fmt.Println(lineinfo)
		}

	}

}
func H_GetListFromString(s string) []string {
	ss := strings.Split(s, "\n")
	resultList := make([]string, 0, len(ss))
	for _, v := range ss {
		resultList = append(resultList, strings.TrimSpace(v))
	}
	return resultList
}

你可能感兴趣的:(Golang)