Regexp digits. Suppose 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.
Example. We introduce the RemoveDigits method, which receives a string and returns a modified string. In RemoveDigits, we call MustCompile to create a regexp.
Part 1 We have 3 example strings and call RemoveDigits on each of them, and print the output strings from RemoveDigits.
Part 2 In RemoveDigits, we must compile a regular expression with regexp.MustCompile. The "\d" indicates digit characters (0 through 9).
Part 3 We call 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.