Golang 从片断中提取正则表达式
正则表达式是一个定义搜索模式的字符序列。Go语言支持正则表达式。
在 Go regexp 中,你可以借助 Find() 方法在给定的字符串中找到一个正则表达式。该方法返回一个片断,该片断持有正则表达式原始片断中最左边的匹配文本。如果没有找到匹配,则返回nil。这个方法是在regexp包中定义的,所以要访问这个方法,你需要在你的程序中导入regexp包。
语法
func (re *Regexp) Find(s []byte) []byte
例1 :
// Go program to illustrate how to
// find regexp from the given slice
package main
import (
"fmt"
"regexp"
)
// Main function
func main() {
// Finding regexp from the
// given slice of bytes
// Using Find() method
m := regexp.MustCompile(`geeks?`)
fmt.Printf("%q\n", m.Find([]byte(`GeeksgeeksGeeks, geeks`)))
fmt.Printf("%q\n", m.Find([]byte(`Hello! geeksForGEEKs`)))
fmt.Printf("%q\n", m.Find([]byte(`I like Go language`)))
fmt.Printf("%q\n", m.Find([]byte(`Hello, Welcome`)))
}
输出
"geeks"
"geeks"
""
""
例2 :
// Go program to illustrate how to
// find regexp from the given slice
package main
import (
"fmt"
"regexp"
)
// Main function
func main() {
// Finding regexp from
// the given slice
// Using Find() method
m := regexp.MustCompile(`language`)
res := m.Find([]byte(`I like Go language this language is "+
"very easy to learn and understand`))
if res == nil {
fmt.Printf("Found: %q ", res)
} else {
fmt.Printf("Found: %q", res)
}
}
输出
Found: "language"
极客教程