Process multilingual text safely
Process multilingual text safely
A Go string is a sequence of bytes and may contain invalid UTF-8. In valid UTF-8, a rune represents a Unicode code point, not necessarily a complete user-perceived character. Use utf8.ValidString at a boundary that requires valid UTF-8, and distinguish byte length, rune count and grapheme clusters.
package main
import ( "fmt" "unicode/utf8")
func main() { s := "سلام" fmt.Println(len(s), utf8.RuneCountInString(s), utf8.ValidString(s)) for i, r := range s { fmt.Printf("%d:%c;", i, r) } fmt.Println()}The four Persian code points each occupy two bytes in this string. range iterates over decoded runes and supplies byte offsets; arbitrary byte slicing can break a UTF-8 sequence. Converting to []rune helps when indexing code points, but can allocate and does not segment grapheme clusters. Go does not automatically normalize canonically equivalent sequences.
Expected output:
8 4 true0:س;2:ل;4:ا;6:م;Validate and classify text
package main
import ( "fmt" "regexp" "strings" "unicode" "unicode/utf8")
func main() { bad := string([]byte{0xff}) fmt.Println(utf8.ValidString(bad)) fmt.Printf("%q\n", strings.ToValidUTF8(bad, "?")) fmt.Println(unicode.IsDigit('۳'), regexp.MustCompile(`^\d$`).MatchString("۳")) fmt.Println("é" == "é", utf8.RuneCountInString("é"))}ToValidUTF8 replaces runs of invalid UTF-8 bytes with the chosen string; reject invalid input instead when exact identity matters. Unicode IsDigit recognizes decimal digits beyond ASCII, but regex \d is ASCII-only; use \p{Nd} if the contract allows Unicode decimal digits. Precomposed é and e plus combining acute are unequal as byte strings. Normalization, locale-sensitive sorting, grapheme segmentation and bidirectional display require explicit policies and suitable libraries; never assume case folding solves all identity or spoofing concerns.
Expected output:
false"?"true falsefalse 2Try it locally
Check whether ۱۲۳ is valid UTF-8, count its runes and test it against ^\p{Nd}+$. Print the three results on one line.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text processing 07: Process multilingual text safely
Check the lesson objective before moving on.
What does len(s) count for a Go string?
Do canonically equivalent Unicode spellings automatically compare equal in Go?