2025年5月16日 00:44:37 星期五

go笔记:正则表达式

简单使用

如果要使用go语言的正则进行匹配,则需要先compile一个正则对象。这个对象是可复用的:

  1. reNews, err := regexp.Compile("^([0-9]*).html")
  2. result := reNews.FindAllStringSubmatch(inputStr, -1)
  3. // 如果匹配
  4. if k == 0 && len(result) > 0 {
  5. newsID := result[0][1]
  6. log.Info("TestRouter1 news id is %s", newsID)
  7. }

就是这么简单。蛤。

group命名参数

使用命名参数:

  1. func GetAllSub(re *regexp.Regexp, inputStr string) ([]map[string]string, error) {
  2. matches := re.FindAllStringSubmatch(inputStr, -1)
  3. groupNames := re.SubexpNames()
  4. ret := make([]map[string]string, 0)
  5. for _, match := range matches {
  6. tpRet := make(map[string]string)
  7. for i, groupName := range groupNames {
  8. if groupName == "" {
  9. continue
  10. }
  11. if i >= len(match) {
  12. return nil, fmt.Errorf("groupName:%v, index:%v,%v not found", groupName, i, match)
  13. }
  14. tpRet[groupName] = match[i]
  15. }
  16. ret = append(ret, tpRet)
  17. }
  18. return ret, nil
  19. }
  20. re := regexp.MustCompile(`type\s+(?P<strName>[a-z0-9A-Z]*)\s+struct\s*{|type\s+(?P<itName>[a-z0-9A-Z]+)\s+interface\s*{`)
  21. ret, err := GetAllSub(re, `type hello struct{
  22. }
  23. type world interface{
  24. }`)
  25. log.Printf("groupNames:%v %v\n", ret, err)
  26. // [{"itName":"","strName":"hello"},{"itName":"world","strName":""}] <nil>

来自 大脸猫 写于 2017-09-07 10:35 -- 更新于2021-01-11 13:13 -- 0 条评论

0条评论

字体
字号


评论: