Skip to main content
同阙
Just for gopher
View all authors

Regexp

· 2 min read
同阙
Just for gopher
前往测试网站

使用示例

package main

import (
"fmt"
"regexp"
)

func main() {
re := regexp.MustCompile(`\d+`)
text := "abc123def456"

fmt.Println("是否匹配:", re.MatchString(text))
fmt.Println("第一个匹配:", re.FindString(text))
fmt.Println("所有匹配:", re.FindAllString(text, -1))

replaced := re.ReplaceAllString(text, "#")
fmt.Println("替换结果:", replaced)
}

// 输出:
// 是否匹配: true
// 第一个匹配: 123
// 所有匹配: [123 456]
// 替换结果: abc#def#

常用方法速查表

方法名说明
MatchString是否匹配字符串
FindString返回第一个匹配的字符串
FindAllString返回所有匹配的字符串
ReplaceAllString替换所有匹配的内容
FindStringSubmatch获取分组匹配
ReplaceAllStringFunc函数式替换匹配内容

常见正则表达式语法(RE2)

.     任意字符
\d 数字(相当于 [0-9])
\w 单词字符(字母、数字、下划线)
+ 匹配一个或多个
* 匹配零个或多个
? 匹配零个或一个
^ 匹配行首
$ 匹配行尾
[] 字符集
() 分组
| 或运算

多行模式支持用 (?m) 写在正则前缀中启用,例如:(?m)^abc$


进阶示例:函数式替换

package main

import (
"fmt"
"regexp"
)

func main() {
re := regexp.MustCompile(`\d+`)
result := re.ReplaceAllStringFunc("价格: 123 元", func(s string) string {
return "[" + s + "]"
})
fmt.Println(result)
}

// 输出:价格: [123] 元

Gorm

· 3 min read
同阙
Just for gopher
前往官网

创建数据库连接

import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

func main() {
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// 使用 db 对象执行数据库操作
}

CRUD

package main

import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

type User struct {
gorm.Model
Name string `gorm:"default:1"`
}

func main() {
dsn := "host=localhost user=testuser password=testpass dbname=testdb port=5432 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
db = db.Debug()
if err != nil {
panic("failed to connect database")
}
//重置练习表
err = db.Migrator().DropTable(&User{})
if err != nil {
panic("failed to drop table")
}
err = db.AutoMigrate(&User{})
if err != nil {
panic("failed to migrate")
}
users := []User{
{Name: "张三"},
{Name: "李四"},
{Name: "王五"},
}
result := db.Create(&users)
if result.Error != nil {
panic("failed to create test data")
}

//TODO:

}

2025, 你好

· One min read
同阙
Just for gopher
tip

2025,比以前更好。

追风赶月莫停留,平芜尽处是春山

至此鲜花赠自己,纵马踏花向自由

2025,你好!

Go start

· One min read
同阙
Just for gopher
前往细节

官网安装

前往 Go 官网 下载并安装 Go,建议选择默认安装选项,一键点击下一步,安装程序会自动为你完成大部分配置。

代理更换(推荐)

go env -w GOPROXY=https://goproxy.cn,https://mirrors.cloud.tencent.com/go/,https://mirrors.aliyun.com/goproxy/,direct

常用工具下载

Hello World

· One min read
同阙
Just for gopher
tip

你好 世界!

package main

import "fmt"

func main() {
fmt.Println("Hello, World!")
}