在Go语言中使用正则表达式来识别常见模式

huangapple go评论83阅读模式
英文:

Using regular expressions in Go to Identify a common pattern

问题

我正在尝试解析这个字符串 goats=1\r\nalligators=false\r\ntext=works

contents := "goats=1\r\nalligators=false\r\ntext=works"

compile, err := regexp.Compile("([^#\\s=]+)=([a-zA-Z0-9.]+)")
if err != nil {
    return
}

matchString := compile.FindAllStringSubmatch(contents, -1)

我的输出结果是 [[goats=1 goats 1] [alligators=false alligators false] [text=works text works]]

我在表达式中做错了什么,导致 goats=1 也被认为是有效的?我只想要 [[goats 1]...]。

英文:

I'm trying to parse this string goats=1\r\nalligators=false\r\ntext=works.

contents := "goats=1\r\nalligators=false\r\ntext=works"


	compile, err := regexp.Compile("([^#\\s=]+)=([a-zA-Z0-9.]+)")
	if err != nil {
		return
	}

	matchString := compile.FindAllStringSubmatch(contents, -1)

my Output looks like [[goats=1 goats 1] [alligators=false alligators false] [text=works text works]]

What I'm I doing wrong in my expression to cause goats=1 to be valid too? I only want [[goats 1]...]

答案1

得分: 1

另一种方法是使用strings包:

package main

import (
   "fmt"
   "strings"
)

func parse(s string) map[string]string {
   m := make(map[string]string)
   for _, kv := range strings.Split(s, "\r\n") {
      a := strings.Split(kv, "=")
      m[a[0]] = a[1]
   }
   return m
}

func main() {
   m := parse("goats=1\r\nalligators=false\r\ntext=works")
   fmt.Println(m) // map[alligators:false goats:1 text:works]
}

https://golang.org/pkg/strings

英文:

For another approach, you can use the strings package instead:

package main

import (
   "fmt"
   "strings"
)

func parse(s string) map[string]string {
   m := make(map[string]string)
   for _, kv := range strings.Split(s, "\r\n") {
      a := strings.Split(kv, "=")
      m[a[0]] = a[1]
   }
   return m
}

func main() {
   m := parse("goats=1\r\nalligators=false\r\ntext=works")
   fmt.Println(m) // map[alligators:false goats:1 text:works]
}

https://golang.org/pkg/strings

huangapple
  • 本文由 发表于 2021年5月24日 06:24:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/67664919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定