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
+5.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+4.8k JavaScript: Add marker function on Google Map
+8.4k Golang: Prevent over writing file with md5 hash
+17.8k Golang : delete and modify XML file content
+8k Golang : Gomobile init produce "iphoneos" cannot be located error
+36.7k Golang : Save image to PNG, JPEG or GIF format.
+7.5k Golang : Scanf function weird error in Windows
+6.1k PHP : How to check if an array is empty ?
+8.9k Golang : Sort lines of text example
+6k Linux/MacOSX : Search for files by filename and extension with find command
+12.8k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+12.8k Golang : zlib compress file example