@@ -8,6 +8,18 @@ import (
8
8
// Go offers built in support for regular expressions
9
9
func Run () {
10
10
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>" )
11
23
}
12
24
13
25
// Check if a string has any matches of a given pattern.
@@ -18,3 +30,14 @@ func stringContainsAnyMatch(pattern string, str string) bool {
18
30
}
19
31
return match
20
32
}
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