输入格式非常简单,您可以简单地使用在strings.IndexRune()以下位置实现的字符搜索:
s := `"Algorithms 1" by Robert Sedgewick`
s = s[1:] // Exclude first double qote
x := strings.IndexRune(s, '"') // Find the 2nd double quote
title := s[:x] // Title is between the 2 double qotes
author := s[x+5:] // Which is followed by " by ", exclude that, rest is author
Run Code Online (Sandbox Code Playgroud)
打印结果:
fmt.Println("Title:", title)
fmt.Println("Author:", author)
Run Code Online (Sandbox Code Playgroud)
输出:
Title: Algorithms 1
Author: Robert Sedgewick
Run Code Online (Sandbox Code Playgroud)
在Go Playground尝试一下.
另一个解决方案是使用strings.Split():
s := `"Algorithms 1" by Robert Sedgewick`
parts := strings.Split(s, `"`)
title := parts[1] // First part is empty, 2nd is title
author := parts[2][4:] // 3rd is author, but cut off " by "
Run Code Online (Sandbox Code Playgroud)
输出是一样的.在Go Playground尝试一下.
如果我们切断第一个双引号,我们可能会通过分隔符进行拆分
`" by `
Run Code Online (Sandbox Code Playgroud)
如果我们这样做,我们将有两个部分:标题和作者.由于我们切断了第一个双引号,分隔符只能位于标题的末尾(标题不能按照您的规则包含双引号):
s := `"Algorithms 1" by Robert Sedgewick`
parts := strings.Split(s[1:], `" by `)
title := parts[0] // First part is exactly the title
author := parts[1] // 2nd part is exactly the author
Run Code Online (Sandbox Code Playgroud)
在Go Playground尝试一下.
如果在完成上述所有解决方案之后您还想使用正则表达式,那么您可以这样做:
使用括号来定义要输出的子匹配.您需要2个部分:引号和后面的作者之间的标题by.您可以使用regexp.FindStringSubmatch()获取匹配的部分.请注意,返回切片中的第一个元素将是完整输入,因此相关部分是后续元素:
s := `"Algorithms 1" by Robert Sedgewick`
r := regexp.MustCompile(`"([^"]*)" by (.*)`)
parts := r.FindStringSubmatch(s)
title := parts[1] // First part is always the complete input, 2nd part is the title
author := parts[2] // 3rd part is exactly the author
Run Code Online (Sandbox Code Playgroud)
在Go Playground尝试一下.