Go regexp按组获取匹配项
我想解析一个字符串,并得到两个引号内的子字符串 主题 图案 后果 密码 使现代化 串Go regexp按组获取匹配项,go,Go,我想解析一个字符串,并得到两个引号内的子字符串 主题 图案 后果 密码 使现代化 串 query="tag1 tag2 tag3" foo="wee" 火柴 tag1 tag2 tag3 regexp不接受数字s/[a-z]/[a-z0-9]/ regexp不接受数字s/[a-z]/[a-z0-9]/ 首先,图案与数字不匹配。您可能希望将其更改为: var re = regexp.MustCompile(`query="(.*)"`) 然后,为了获得子字符串,您可以使用FindStringS
query="tag1 tag2 tag3" foo="wee"
火柴
tag1 tag2 tag3
regexp不接受数字s/[a-z]/[a-z0-9]/
regexp不接受数字s/[a-z]/[a-z0-9]/
首先,图案与数字不匹配。您可能希望将其更改为:
var re = regexp.MustCompile(`query="(.*)"`)
然后,为了获得子字符串,您可以使用FindStringSubmatch:
输出:
找到:[tag1 tag2]
然后,为了将字符串拆分为单独的标记,我建议首先使用,模式将与数字不匹配。您可能希望将其更改为:
var re = regexp.MustCompile(`query="(.*)"`)
然后,为了获得子字符串,您可以使用FindStringSubmatch:
输出:
找到:[tag1 tag2]
然后,为了将字符串拆分为单独的标记,我建议使用您可以提取整个标记字符串,然后拆分它
输出:[tag1 tag2 tag3]您可以提取整个标记字符串,然后将其拆分
输出:[tag1 tag2 tag3]已更新我的问题。。我需要匹配每个标记tag1 tag2和tag3 indeside query=@clarkk好吧,如果你读过我的答案,你会发现我建议使用strings.Split来处理这个问题。您接受的答案中使用的正是后来的答案。已更新我的问题。。我需要匹配每个标记tag1 tag2和tag3 indeside query=@clarkk好吧,如果你读过我的答案,你会发现我建议使用strings.Split来处理这个问题。SubexpNames是正则表达式的方法,它不适用于查找…匹配操作的结果。SubexpNames是正则表达式的方法,它不适用于查找…匹配操作的结果。
package main
import (
"fmt"
"regexp"
)
var re = regexp.MustCompile(`query="([a-z ]*)"`)
func main() {
match := re.FindStringSubmatch(`query="tag1 tag2"`)
result := make(map[string]string)
for i, name := range re.SubexpNames() {
result[name] = match[i]
}
fmt.Printf("by name: %v\n", result)
}
query="tag1 tag2 tag3" foo="wee"
package main
import "fmt"
import "regexp"
func main() {
var str string = `query="tag1 tag2 tag3" foo="wee"`
re := regexp.MustCompile(`query="(([a-z0-9]+) ?)*"`)
match := re.FindStringSubmatch(str)
if len(match) == 0 {
fmt.Print("no matches")
} else {
result := make(map[string]string)
for i, name := range re.SubexpNames(){
result[name] = match[i]
}
fmt.Print(result)
}
}
var re = regexp.MustCompile(`query="(.*)"`)
match := re.FindStringSubmatch(`query="tag1 tag2"`)
if len(match) == 2 {
fmt.Printf("Found: [%s]\n", match[1])
} else {
fmt.Println("No match found", match)
}
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
var str string = `query="tag1 tag2 tag3" foo="wee"`
re := regexp.MustCompile(`query="(.+?)"`)
match := re.FindStringSubmatch(str)
if len(match) == 2 {
fmt.Println(strings.Split(match[1], " "))
}
}