diff --git a/examples.txt b/examples.txt index 85d7d4b..27558cd 100644 --- a/examples.txt +++ b/examples.txt @@ -45,7 +45,7 @@ Defer Collection Functions String Functions # String Formatting -# Regexs +Regular Expressions # Bytes # JSON # Time diff --git a/examples/regexs/regexs.go b/examples/regexs/regexs.go deleted file mode 100644 index 5394db3..0000000 --- a/examples/regexs/regexs.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import "regexp" -import "fmt" - -func main() { - m1, _ := regexp.MatchString("p[a-z]+ch", "apple") - m2, _ := regexp.MatchString("p[a-z]+ch", "peach") - fmt.Println(m1) - fmt.Println(m2) - - r1, _ := regexp.Compile("p[a-z]+ch") - fmt.Println(r1.MatchString("apple")) - fmt.Println(r1.MatchString("peach")) -} - -// todo: more -// todo: gsub with regexp -// todo: rename to "Regular Expressions" diff --git a/examples/regexs/regexs.sh b/examples/regexs/regexs.sh deleted file mode 100644 index eb37512..0000000 --- a/examples/regexs/regexs.sh +++ /dev/null @@ -1,5 +0,0 @@ -$ go run regexs.go -false -true -false -true diff --git a/examples/regular-expressions/regular-expressions.go b/examples/regular-expressions/regular-expressions.go new file mode 100644 index 0000000..8d2491a --- /dev/null +++ b/examples/regular-expressions/regular-expressions.go @@ -0,0 +1,40 @@ +// Go offers built-in support for [regular expressions](http://en.wikipedia.org/wiki/Regular_expression). +// Here are some examples of common regexp-related tasks +// in Go. + +package main + +import "fmt" +import "regexp" + +func main() { + + // This tests whether a pattern matches a string. + match, _ := regexp.MatchString("p[a-z]+ch", "apple") + fmt.Println("match:", match) + + // In the above example we used a string pattern + // directly. For other regular expression tasks you'll + // need to `Compile` a `Regexp` struct. + r1, _ := regexp.Compile("p[a-z]+ch") + + // Many methods are available on these structs. Here's + // a match test like we saw earlier. + fmt.Println("match:", r1.MatchString("apple")) + + // + + // When creating top-level constants with regular + // expressions, you can use the `MustCompile` variant + // of the `Compile` function we saw earlier. A plain + // `Compile` won't work for constants because it has 2 + // return values. + cr := regexp.MustCompile("p[a-z]+ch") + fmt.Println("regex:", cr) + +} + +// todo: +// todo: gsub + +// todo: Examples of regular expressions in #golang: https://gobyexample.com/regular-expressions One of the best areas for a "by example" approach IMO. diff --git a/examples/regular-expressions/regular-expressions.sh b/examples/regular-expressions/regular-expressions.sh new file mode 100644 index 0000000..52fb01e --- /dev/null +++ b/examples/regular-expressions/regular-expressions.sh @@ -0,0 +1,4 @@ +$ go run regular-expressions.go +match: false +match: false +regex: p[a-z]+ch