Go语言的strings包提供了丰富的字符串操作函数,strconv包处理字符串与基本类型的转换,regexp包提供正则表达式功能。
字符串特点:Go中字符串是不可变的字节序列,使用UTF-8编码。
场景:用户注册信息验证和处理
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
"unicode/utf8"
)
// 验证邮箱格式
func validateEmail(email string) bool {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
matched, _ := regexp.MatchString(pattern, email)
return matched
}
// 验证手机号格式
func validatePhone(phone string) bool {
pattern := `^1[3-9]\d{9}$`
matched, _ := regexp.MatchString(pattern, phone)
return matched
}
// 处理用户输入
func processUserInput(input string) map[string]interface{} {
result := make(map[string]interface{})
// 清理输入
cleaned := strings.TrimSpace(input)
cleaned = strings.ToLower(cleaned)
// 分割字段(模拟"name:age:email"格式)
fields := strings.Split(cleaned, ":")
if len(fields) < 3 {
return nil
}
result["name"] = fields[0]
// 转换年龄
age, err := strconv.Atoi(strings.TrimSpace(fields[1]))
if err != nil || age < 0 || age > 150 {
result["age"] = "无效年龄"
} else {
result["age"] = age
}
// 验证邮箱
email := strings.TrimSpace(fields[2])
if validateEmail(email) {
result["email"] = email
} else {
result["email"] = "邮箱格式错误"
}
// 统计信息
result["original_length"] = len(input)
result["cleaned_length"] = len(cleaned)
result["rune_count"] = utf8.RuneCountInString(cleaned)
return result
}
func main() {
// 模拟用户输入
userInputs := []string{
"john doe:25:john@example.com",
" ALICE SMITH:30:alice@gmail.com ",
"bob:invalid:bademail",
"李四:28:lisi@example.com",
}
for _, input := range userInputs {
fmt.Printf("处理输入: '%s'\n", input)
result := processUserInput(input)
if result == nil {
fmt.Println(" 错误: 输入格式不正确")
} else {
for k, v := range result {
fmt.Printf(" %s: %v\n", k, v)
}
}
fmt.Println()
}
// 手机号验证
phones := []string{"13812345678", "12345678900", "15887654321"}
for _, phone := range phones {
valid := validatePhone(phone)
fmt.Printf("手机号 %s 验证结果: %t\n", phone, valid)
}
}
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
)
func main() {
text := "订单号: ORD-2023-001, 价格: ¥150.75, 数量: 5, 总计: ¥753.75"
// 使用正则表达式提取信息
// 提取订单号
orderPattern := `ORD-\d{4}-\d{3}`
orderRegex := regexp.MustCompile(orderPattern)
orderNum := orderRegex.FindString(text)
fmt.Println("提取的订单号:", orderNum)
// 提取价格数字
pricePattern := `¥(\d+\.\d+)`
priceRegex := regexp.MustCompile(pricePattern)
priceMatches := priceRegex.FindAllStringSubmatch(text, -1)
fmt.Println("提取的价格:")
for _, match := range priceMatches {
if len(match) > 1 {
fmt.Println(" ", match[1])
}
}
// 字符串构建器
var builder strings.Builder
builder.WriteString("产品清单:\n")
products := []string{"笔记本电脑", "无线鼠标", "机械键盘", "显示器"}
for i, product := range products {
builder.WriteString(strconv.Itoa(i+1))
builder.WriteString(". ")
builder.WriteString(product)
builder.WriteString("\n")
}
fmt.Println("\n" + builder.String())
// 字符串替换和重复
template := "重要通知: {message} | 重复显示: {repeat}"
replaced := strings.Replace(template, "{message}", "系统维护通知", 1)
repeated := strings.Repeat("注意!", 3)
final := strings.Replace(replaced, "{repeat}", repeated, 1)
fmt.Println(final)
// 字符串比较和前缀后缀
url1 := "https://example.com/api/v1/users"
url2 := "https://example.com/api/v1/products"
fmt.Printf("\nURL1 以 https 开头: %t\n", strings.HasPrefix(url1, "https"))
fmt.Printf("URL2 以 users 结尾: %t\n", strings.HasSuffix(url2, "users"))
fmt.Printf("URL1 和 URL2 包含相同API路径: %t\n",
strings.Contains(url1, "/api/v1/") && strings.Contains(url2, "/api/v1/"))
}
strings包提供字符串操作:Contains、Split、Join、Replace、Trim等strconv包处理字符串与基本类型转换:Atoi、Itoa、ParseBool等regexp包提供正则表达式:MatchString、FindString、ReplaceAllString等utf8包或[]rune处理,因为Go中字符串按UTF-8编码