Golang : Use regular expression to get all upper case or lower case characters example
This is an add-on for the previous tutorial on how to get all upper case or lower case characters example. In this example, we will explore the a different version that use a regular expression to achieve the same objective.
Here you go!
package main
import (
"fmt"
"regexp"
)
func removeDelimAndLowerCase(str string) string {
regExp := regexp.MustCompile(`[^[:upper:]]`)
return regExp.ReplaceAllString(str, "")
}
func removeDelimAndUpperCase(str string) string {
regExp := regexp.MustCompile(`[^[:lower:]]`)
return regExp.ReplaceAllString(str, "")
}
func main() {
str := "This a string with some UpperCase Characters."
allUpper := removeDelimAndLowerCase(str)
fmt.Println("All uppercase : ", allUpper)
allLower := removeDelimAndUpperCase(str)
fmt.Println("All lowercase : ", allLower)
}
Output:
All uppercase : TUCC
All lowercase : hisastringwithsomepperaseharacters
NOTES:
It is definitely faster to use regular expression to parse string, but sometimes it can be hard to read for other programmers or your teammates. To keep things simple, try to use non-regular expression solution if possible. Ability is read source code is more important that ability to write codes.
Happy coding!
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+18.5k Golang : Append content to a file
+7.1k Golang : HTTP Server Example
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula
+40.9k Golang : Get hardware information such as disk, memory and CPU usage
+19k Golang : Secure(TLS) connection between server and client
+12.5k Golang : Tutorial on loading GOB and PEM files
+6.8k Swift : Convert (cast) String to Double
+10k How to test Facebook App on localhost ?
+15.4k Golang : File path independent of Operating System
+31.3k Golang : Smarter Error Handling with strings.Contains()