Regexp
digitsSuppose we want to remove all digits from a string
in our Go program. This can be done with the regexp
package, and the ReplaceAllString
method.
In addition, the approach used to remove digits can be used to remove other characters within a range. We use a metacharacter in regexp.MustCompile
to create the pattern.
We introduce the RemoveDigits
method, which receives a string
and returns a modified string
. In RemoveDigits
, we call MustCompile
to create a regexp
.
RemoveDigits
on each of them, and print the output strings from RemoveDigits
.RemoveDigits
, we must compile a regular expression with regexp.MustCompile
. The "\d" indicates digit characters (0 through 9).ReplaceAllString
on the regexp
we just created. We replace matches within the string
with an empty string
, which removes them.package main import ( "fmt" "regexp" ) func RemoveDigits(input string) string { // Part 2: compile the regexp that matches digit characters. re := regexp.MustCompile(`\d`) // Part 3: use ReplaceAllString to replace all digits with an empty string. replacementResult := re.ReplaceAllString(input, "") return replacementResult; } func main() { // Part 1: call RemoveDigits on some example strings containing digits and print results. input1 := "Dot123Net456Perls" result1 := RemoveDigits(input1) fmt.Println(result1) input2 := "101Dalmatations" result2 := RemoveDigits(input2) fmt.Println(result2) input3 := "4 Score" result3 := RemoveDigits(input3) fmt.Println(result3) }DotNetPerls Dalmatations Score
Though it is possible to write rune
-oriented methods that loop over characters, with regexp
methods we often will require less code—and this often results in fewer bugs.