go提供对正则表达式的内置支持。 下面是go中常见的regexp
相关任务的一些例子。
具体的每个函数,可参考示例中的代码 -
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html
string-formatting.go
的完整代码如下所示 -
package main
import "bytes"
import "fmt"
import "regexp"
func main() {
// this tests whether a pattern matches a string.
match, _ := regexp.matchstring("p([a-z]+)ch", "peach")
fmt.println(match)
// above we used a string pattern directly, but for
// other regexp tasks you'll need to `compile` an
// optimized `regexp` struct.
r, _ := regexp.compile("p([a-z]+)ch")
// many methods are available on these structs. here's
// a match test like we saw earlier.
fmt.println(r.matchstring("peach"))
// this finds the match for the regexp.
fmt.println(r.findstring("peach punch"))
// this also finds the first match but returns the
// start and end indexes for the match instead of the
// matching text.
fmt.println(r.findstringindex("peach punch"))
// the `submatch` variants include information about
// both the whole-pattern matches and the submatches
// within those matches. for example this will return
// information for both `p([a-z]+)ch` and `([a-z]+)`.
fmt.println(r.findstringsubmatch("peach punch"))
// similarly this will return information about the
// indexes of matches and submatches.
fmt.println(r.findstringsubmatchindex("peach punch"))
// the `all` variants of these functions apply to all
// matches in the input, not just the first. for
// example to find all matches for a regexp.
fmt.println(r.findallstring("peach punch pinch", -1))
// these `all` variants are available for the other
// functions we saw above as well.
fmt.println(r.findallstringsubmatchindex(
"peach punch pinch", -1))
// providing a non-negative integer as the second
// argument to these functions will limit the number
// of matches.
fmt.println(r.findallstring("peach punch pinch", 2))
// our examples above had string arguments and used
// names like `matchstring`. we can also provide
// `[]byte` arguments and drop `string` from the
// function name.
fmt.println(r.match([]byte("peach")))
// when creating constants with regular expressions
// you can use the `mustcompile` variation of
// `compile`. a plain `compile` won't work for
// constants because it has 2 return values.
r = regexp.mustcompile("p([a-z]+)ch")
fmt.println(r)
// the `regexp` package can also be used to replace
// subsets of strings with other values.
fmt.println(r.replaceallstring("a peach", "<fruit>"))
// the `func` variant allows you to transform matched
// text with a given function.
in := []byte("a peach")
out := r.replaceallfunc(in, bytes.toupper)
fmt.println(string(out))
}
执行上面代码,将得到以下输出结果 -
f:\worksp\golang>go run regular-expressions.go
true
true
peach
[0 5]
[peach ea]
[0 5 1 3]
[peach punch pinch]
[[0 5 1 3] [6 11 7 9] [12 17 13 15]]
[peach punch]
true
p([a-z]+)ch
a <fruit>
a peach