To remove all the digits from a string in Go, you can use a combination of the strings
and unicode
packages.
Here's an example of how you can do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
// The input string with digits
input := "Hello123World456"
// Create a new string builder
var builder strings.Builder
// Iterate over the input string
for _, r := range input {
// If the current character is not a digit, append it to the string builder
if !unicode.IsDigit(r) {
builder.WriteRune(r)
}
}
// Get the resulting string from the string builder
output := builder.String()
// Print the resulting string
fmt.Println(output) // Output: "HelloWorld"
}
This code iterates over the characters in the input string and checks if each character is a digit using the unicode.IsDigit
function. If the character is not a digit, it is appended to a strings.Builder
object. Finally, the resulting string is obtained from the string builder using the String
method.
An other way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main
import (
"fmt"
"regexp"
)
func main() {
Input := "H1e5ll0o"
re := regexp.MustCompile(`\d`)
fmt.Println(Input)
Output := re.ReplaceAllString(Input, "")
fmt.Println(Output) // "Hello"
}