Skip to content

Commit cacdad1

Browse files
committed
50: Regular expression examples
1 parent 89a3fd5 commit cacdad1

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

regex/main.go

+23
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,18 @@ import (
88
// Go offers built in support for regular expressions
99
func Run() {
1010
fmt.Println(stringContainsAnyMatch("^hello.*", "hello world"))
11+
pattern := compiledPattern("^f")
12+
fmt.Println(pattern.MatchString("fo"))
13+
fmt.Println(pattern.MatchString("oof"))
14+
// matches `f` only.
15+
fmt.Println(pattern.FindString("foolproof"))
16+
pattern = compiledPattern("hello.*")
17+
// [3-14] index matching
18+
fmt.Println("index: ", pattern.FindStringIndex("ok hello there"))
19+
// Find information around full matches and sub matches within those full matches
20+
fmt.Println(pattern.FindStringSubmatch("ok hello world test"))
21+
// Replace all occurrences
22+
replaceAllOccurrences("hello[0-9]", "hello1, hello2, hello3, helloX, helloY", "<replaced>")
1123
}
1224

1325
// Check if a string has any matches of a given pattern.
@@ -18,3 +30,14 @@ func stringContainsAnyMatch(pattern string, str string) bool {
1830
}
1931
return match
2032
}
33+
34+
// Compiles are pattern for reuse. Panics if invalid pattern.
35+
func compiledPattern(pattern string) *regexp.Regexp {
36+
return regexp.MustCompile(pattern)
37+
}
38+
39+
func replaceAllOccurrences(pattern string, s string, r string) {
40+
p := regexp.MustCompile(pattern)
41+
result := p.ReplaceAllString(s, r)
42+
fmt.Printf("Replaced %s with %s: %s\n", s, r, result)
43+
}

0 commit comments

Comments
 (0)