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
+15.6k Golang : Read a file line by line
+4.8k Python : Convert(cast) bytes to string example
+33.6k Golang : Proper way to set function argument default value
+9.5k Golang : Turn string or text file into slice example
+7.7k Golang : Check from web if Go application is running or not
+15.2k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+13.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+10.8k Golang : Create S3 bucket with official aws-sdk-go package
+22.8k Golang : Get ASCII code from a key press(cross-platform) example
+12.6k Golang : Get terminal width and height example
+16.6k Golang : How to generate QR codes?
+8.1k Golang : Generate Datamatrix barcode