在之前的教程中,我们已经解释了如何在Golang中创建REST API。在本教程中,我们将解释如何在Golang中使用正则表达式。
正则表达式或者说regex是一个字符序列,用来定义搜索模式。它是大多数编程语言中使用的强大技术。正则表达式提供了快速的解决方案,可以在一行代码中处理所有搜索、替换、提取、模式匹配等问题,而不是写很多行代码。
在Golang中,有一个内置的包regexp ,用于正则表达式。该包使用RE2语法标准,也被其他语言如Python、C和Perl所使用。该包包含处理正则表达式的函数。主要的正则函数有MatchString(),FindString(),FindStringIndex(),FindStringSubmatch(),FindStringSubmatchIndex(),Compile(),MustCompile() 等。
因此,在本教程中,我们将用实例来解释正则表达式的工作中的regex函数。
1.匹配字符串方法
我们可以使用regex包中的方法regexp.MatchString() 来匹配子串。在下面的示例代码中,我们想测试字符串是否以G字符开始。我们将使用 caret(^)来匹配字符串中文本的开头。因此我们将使用子串"^G "来匹配字符串。
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Golang regular expressions example"
match, err := regexp.MatchString(`^G`, str)
fmt.Println("Match: ", match, " Error: ", err)
}
当我们运行上面的示例代码时,它将匹配子串并返回true。所以它将显示如下的输出。
Match: true Error: <nil>
2.编译或必须编译方法
我们可以使用Compile() 或MustCompile() 方法来创建regex的对象。如果正则表达式无效,Compile() 方法会返回错误,而当有无效的正则表达式时,MustCompile() 运行时没有任何错误。所以建议使用Compile() 来创建regex对象。我们可以像下面这样使用这些方法。
regexp1, err := regexp.Compile(`regexp`)
regexp2 := regexp.MustCompile(`regexp`)
3.查找字符串方法
我们可以使用FindString() 方法来获得第一个匹配的结果。如果没有匹配,返回值是一个空字符串。在下面的示例代码中,我们将匹配文本恳求,在字符串的末尾退出。如果字符串匹配,它将返回匹配结果,否则返回空字符串。在这个示例代码中,我们还使用了Compile() 方法来创建一个Regexp对象。如果我们不希望得到一个错误,我们可以使用MustCompile() 方法。
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Golang regular expressions example"
regexp := regexp.Compile("ple$")
fmt.Println(regexp.FindString(str))
}
当我们运行上述代码时,它显示了以下匹配字符串。
Match: ple Error: <nil>
4.查找字符串索引方法
我们可以使用FindStringIndex() 方法来获得正则表达式最左边匹配的开始和结束索引。如果没有匹配,它将返回null值。
在下面的示例代码中,我们将找到文本p在字符串中的索引。
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Golang regular expressions example"
regexp, err := regexp.Compile(`p`)
match := regexp.FindStringIndex(str)
fmt.Println("Match: ", match, " Error: ", err)
}
当我们运行上述示例代码时,它将返回以下输出。
Match: [17 18] Error: <nil>
5.5.FindStringSubmatch方法
我们可以使用该方法FindStringSubmatch() ,找到与REGEX模式匹配的最左边的子串。如果没有匹配,那么它将返回一个空值。
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Golang regular expressions example"
regexp, err := regexp.Compile(`l([a-z]+)g`)
match := regexp.FindStringSubmatch(str)
fmt.Println("Match: ", match, " Error: ", err)
}
当我们运行上面的示例代码时,它将返回以下结果,即最左边的子串与之匹配。
Match: [lang an] Error: <nil>
6.FindStringSubmatchIndex方法
我们可以使用该方法FindStringSubmatchIndex() 来查找与REGEX模式相匹配的最左边的子串的索引。
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Golang regular expressions example"
regexp, err := regexp.Compile(`l([a-z]+)g`)
match := regexp.FindStringSubmatchIndex(str)
fmt.Println("Match: ", match, " Error: ", err)
}
当我们运行上面的例子代码时,它将返回以下的结果,其中包括匹配的最左边的子串的索引。
Match: [2 6 3 5] Error: <nil>
你可能也喜欢:
- 用Golang创建REST API
- 如何在Golang中删除文件
- 在Golang中使用结构体
- 在Golang中使用日期和时间
- 如何在Golang中进行HTTP请求
- 在Golang中使用通道
- 在Golang中使用Goroutines的并发性
- 在Golang中使用地图
- 在Golang中的归整和解整
- 在Golang中上传AWS S3文件
- 用Golang写数据到CSV文件
- [如何使用 Golang 读取 CSV 文件](How to Read CSV File using Golang)
- 使用Golang解析JSON数据
- 使用Golang逐行读取文件
Golang中的正则表达式》一文首次出现在WD上。