Go 正则表达式基础教程文档
收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體
Go Regex
Go Regex 包用于搜索字符串。要搜索字符串,我们需要提供字符串的模式。
我们需要将模式编译成正则表达式对象,以便我们可以通过它调用方法。
可以使用 compile() 和 mustcompile() 函数检索正则表达式对象。现在我们可以使用 FindString()、FindStringSubmatch()、FindStringIndex() 等函数来查找字符串。
Go Regex Example 1
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(".com") fmt.Println(re.FindString("google.com")) fmt.Println(re.FindString("abc.org")) fmt.Println(re.FindString("fb.com")) }
输出:
.com .com
FindString() 方法返回具有最左边匹配文本的字符串。如果未找到匹配项,则返回空字符串。
转到正则表达式示例 2
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(".com") fmt.Println(re.FindStringIndex("google.com")) fmt.Println(re.FindStringIndex("abc.org")) fmt.Println(re.FindStringIndex("fb.com")) }
输出:
[6 10] [] [2 6]
Go Regex Example 3
我们还可以使用 FindStringSubmatch() 方法,该方法返回包含最左边匹配和匹配文本的字符串片段。如果未找到匹配项,则返回值为空字符串。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile("f([a-z]+)ing") fmt.Println(re.FindStringSubmatch("flying")) fmt.Println(re.FindStringSubmatch("abcfloatingxyz")) }
输出:
[flying ly]
[floating loat]
Process finished with exit code 0