Golang教程-Go正则表达式
Go正则表达式
Go正则表达式包用于搜索字符串。要搜索一个字符串,我们需要提供一个字符串的模式。
我们需要将模式编译成正则表达式对象,以便我们可以通过它调用方法。
可以使用compile()和mustcompile()函数来获取正则表达式对象。现在我们可以使用函数来查找字符串,例如FindString()、FindStringSubmatch()、FindStringIndex()等。
Go正则表达式示例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()方法返回一个具有最左匹配文本的字符串。如果没有找到匹配项,将返回空字符串。
Go正则表达式示例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正则表达式示例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