解析特定格式的输入

cal*_*tie 2 regex string parsing go

我们说我有以下字符串:"Algorithms 1" by Robert Sedgewick.这是从终端输入的.

此字符串的格式始终为:
1.以双引号开头
2.后跟字符(可能包含空格)
3.后跟双引号
4.后跟空格
5.后跟单词"by"
6.后跟空格
7.后跟字符(可能包含空格)

知道上述格式,我该如何阅读?

我尝试过使用fmt.Scanf()但是会将每个空格后的单词视为单独的值.我查看了正则表达式但是我无法弄清楚是否有一个函数可以用来获取值而不仅仅是测试有效性.

icz*_*cza 5

1)使用字符搜索

输入格式非常简单,您可以简单地使用在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尝试一下.

2)分裂

另一个解决方案是使用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尝试一下.

3)"棘手"分裂

如果我们切断第一个双引号,我们可能会通过分隔符进行拆分

`" 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尝试一下.

4)使用正则表达式

如果在完成上述所有解决方案之后您还想使用正则表达式,那么您可以这样做:

使用括号来定义要输出的子匹配.您需要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尝试一下.