Menu

  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay
  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay

使用Go语言进行文本处理

24
Aug
2016

使用Go语言进行文本处理

By Alex
/ in Go
0 Comments
编程语言特性
字符串的表示 

双引号包围。支持多行字符串,使用反引号包围:

Go
1
2
3
str := `This string
    will have
    tabs in it`
切片操作
Go
1
2
3
4
5
str := "12345"
println(str[0:1]) // 1
println(str[0:4]) // 1234
println(str[:])   // 12345
println(str[1:])  // 12345 
获取长度

built-in库支持对多种数据类型获取长度,包括字符串:

Go
1
len("hello")
取字符
Go
1
str[idx]
类型转换
Go
1
2
3
4
5
6
var s string = "this is a string"
var b []byte
// 字符串转换为byte切片
b = []byte(s)
// byte切换转换为字符串
s = string(b) 
相关包
strings

提供基本的字符串处理函数:

Go
1
2
3
4
5
6
7
8
9
10
11
12
13
strings.Contains("test", "es")           // 包含子串测试
strings.Count("test", "t")               // 子串出现个数测试
strings.HasPrefix("test", "te")          // 前缀测试
strings.HasSuffix("test", "st")          // 后缀测试
strings.Index("test", "e")               // 获取起始位置
strings.Join([]string{"a", "b"}, "-")    // 连接数组为字符串
strings.Repeat("a", 5)                   // 重复N次
strings.Replace("foo", "o", "0", -1)     // 子串替换
strings.Split("a-b-c-d-e", "-")          // 字符串分割
strings.ToLower("TEST")                  // 大写转换
strings.ToUpper("test")                  // 小写转换
strings.NewReader("str")                 // 获取一个Reader
strings.TrimSpace(" str \n")             // 返回去除首尾所有Unicode空白符后的切片
bytes

可以利用此包创建字符串缓冲区,类似于Java的StringBuffer:

Go
1
2
3
4
5
6
7
var buffer bytes.Buffer
 
for i := 0; i < 1000; i++ {
    buffer.WriteString("hello")
}
 
fmt.Println(buffer.String())
bufio

此包提供的Scanner可以逐行迭代处理字符串:

Go
1
2
3
4
scanner := bufio.NewScanner(strings.NewReader(str)))
for scanner.Scan() {
    buf.WriteString(scanner.Text())
}
strconv

可用于将任何类型转换为字符串:

Go
1
2
i := 123
t := strconv.Itoa(i)
math/rand 

可以创建随机字符串:

Go
1
2
3
4
5
6
7
8
9
10
11
var source = rand.NewSource(time.Now().UnixNano())
 
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
 
func RandString(length int) string {
    b := make([]byte, length)
    for i := range b {
        b[i] = charset[source.Int63()%int64(len(charset))]
    }
    return string(b)
}
bufio

可以实现逐行处理:

Go
1
2
3
4
5
6
7
8
9
10
var (
    reader   *bufio.Reader = bufio.NewReader(strings.NewReader(value))
    isPrefix bool          = false
    line     []byte        = nil
    err      error         = nil
)
for !isPrefix && err == nil {
    line, isPrefix, err = reader.ReadLine()
    println(string(line))
}
fmt

用于进行C风格的字符串格式化。动词列表:

动词 说明 动词 说明
%v 默认格式下的值 %#v Go语法格式下的值
%T Go语法格式下的类型 %% 输出%
%t 输出Bool值 %b 二进制
%c 输出Unicode代码点对应的字符 %d 十进制
%o 八进制 %O 前缀0od的八进制
%q 单引号包含的字符,已经安全转义 %x 十六进制,使用小写字母
%X 十六进制,使用大写字母 %U Unicode格式,U+1234
%e 科学计数法,小写e %E 科学计数法,大写E
%f 浮点数 %F 浮点数
%g 自动选择%f或%e %G 自动选择%F或%E
%s 字符串或切片未解释的枝节 %q 双引号包含的字符,已经安全转义
%x 十六进制,每字节显示为2小写字母 %X 十六进制,每字节显示为2大写字母
%p 切片首元素的地址,指针地址    

对于浮点数,可以指定精度:

示例 说明
%f 默认宽度,默认精度
%9f 宽度8,默认精度
%.2f 默认宽度,精度2
%9.2f 宽度9,精度2
%9.f 宽度9,精度0

示例:

Go
1
fmt.Sprintf("%6.2f", 12.0) 
正则式

包regexp实现了正则式搜索和匹配。Go语言使用类似Perl/Python等语言的正则式,所有字符都是UTF-8编码的代码点。

编译正则式
Go
1
validMobileNo := regexp.MustCompile(`((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}`)
匹配字符串

如果目标字符串匹配正则式,则返回true:

Go
1
2
println(validMobileNo.MatchString("Tel: 18888888888"))       //true
println(validMobileNo.MatchString("188"))                    //false
查找字符串

在目标字符串中检索并返回匹配正则式的子串:

Go
1
println(validMobileNo.FindString("Tel: 18888888888 "))       // 18888888888

也可以返回匹配子串的索引范围,如果不匹配返回nil:

Go
1
fmt.Println(validMobileNo.FindStringIndex("18888888888 "))   // [0 11]
分组查找

返回整个匹配的子串,以及每个分组:

Go
1
2
3
4
5
//                           分组1                    分组2
love := regexp.MustCompile(`([A-Z][a-z]+)\s+loves\s+([A-Z][a-z]+)`)
fmt.Printf("%q\n", love.FindStringSubmatch("Alex loves Meng"))
// 整个子串             分组1  分组2
// ["Alex loves Meng" "Alex" "Meng"]
替换字符串

用字面值替换:

Go
1
2
alex := regexp.MustCompile(`(Alex)`)
println(alex.ReplaceAllLiteralString("Hello Alex", "${1}Wong")) // Hello ${1}Wong

用捕获的分组替换:

Go
1
println(alex.ReplaceAllString("Hello Alex", "${1} Wong"))       // Hello Alex Wong

 

← Ubuntu下使用Kerberos
Next Post →

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Related Posts

  • Kuberentes客户端编程
  • Go语言系统编程
  • Goland知识集锦
  • Protocol Buffers初探
  • Go语言中的模板引擎

Recent Posts

  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
  • A Comprehensive Study of Kotlin for Java Developers
  • 背诵营笔记
  • 利用LangChain和语言模型交互
  • 享学营笔记
ABOUT ME

汪震 | Alex Wong

江苏淮安人,现居北京。目前供职于腾讯云,专注容器方向。

GitHub:gmemcc

Git:git.gmem.cc

Email:gmemjunk@gmem.cc@me.com

ABOUT GMEM

绿色记忆是我的个人网站,域名gmem.cc中G是Green的简写,MEM是Memory的简写,CC则是我的小天使彩彩名字的简写。

我在这里记录自己的工作与生活,同时和大家分享一些编程方面的知识。

GMEM HISTORY
v2.00:微风
v1.03:单车旅行
v1.02:夏日版
v1.01:未完成
v0.10:彩虹天堂
v0.01:阳光海岸
MIRROR INFO
Meta
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
Recent Posts
  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
    In this blog post, I will walk ...
  • A Comprehensive Study of Kotlin for Java Developers
    Introduction Purpose of the Study Understanding the Mo ...
  • 背诵营笔记
    Day 1 Find Your Greatness 原文 Greatness. It’s just ...
  • 利用LangChain和语言模型交互
    LangChain是什么 从名字上可以看出来,LangChain可以用来构建自然语言处理能力的链条。它是一个库 ...
  • 享学营笔记
    Unit 1 At home Lesson 1 In the ...
  • K8S集群跨云迁移
    要将K8S集群从一个云服务商迁移到另外一个,需要解决以下问题: 各种K8S资源的迁移 工作负载所挂载的数 ...
  • Terraform快速参考
    简介 Terraform用于实现基础设施即代码(infrastructure as code)—— 通过代码( ...
  • 草缸2021
    经过四个多月的努力,我的小小荷兰景到达极致了状态。

  • 编写Kubernetes风格的APIServer
    背景 前段时间接到一个需求做一个工具,工具将在K8S中运行。需求很适合用控制器模式实现,很自然的就基于kube ...
  • 记录一次KeyDB缓慢的定位过程
    环境说明 运行环境 这个问题出现在一套搭建在虚拟机上的Kubernetes 1.18集群上。集群有三个节点: ...
  • eBPF学习笔记
    简介 BPF,即Berkeley Packet Filter,是一个古老的网络封包过滤机制。它允许从用户空间注 ...
  • IPVS模式下ClusterIP泄露宿主机端口的问题
    问题 在一个启用了IPVS模式kube-proxy的K8S集群中,运行着一个Docker Registry服务 ...
  • 念爷爷
      今天是爷爷的头七,十二月七日、阴历十月廿三中午,老人家与世长辞。   九月初,回家看望刚动完手术的爸爸,发

  • 6 杨梅坑

  • liuhuashan
    深圳人才公园的网红景点 —— 流花山

  • 1 2020年10月拈花湾

  • 内核缺陷触发的NodePort服务63秒延迟问题
    现象 我们有一个新创建的TKE 1.3.0集群,使用基于Galaxy + Flannel(VXLAN模式)的容 ...
  • Galaxy学习笔记
    简介 Galaxy是TKEStack的一个网络组件,支持为TKE集群提供Overlay/Underlay容器网 ...
TOPLINKS
  • Zitahli's blue 91 people like this
  • 梦中的婚礼 64 people like this
  • 汪静好 61 people like this
  • 那年我一岁 36 people like this
  • 为了爱 28 people like this
  • 小绿彩 26 people like this
  • 彩虹姐姐的笑脸 24 people like this
  • 杨梅坑 6 people like this
  • 亚龙湾之旅 1 people like this
  • 汪昌博 people like this
  • 2013年11月香山 10 people like this
  • 2013年7月秦皇岛 6 people like this
  • 2013年6月蓟县盘山 5 people like this
  • 2013年2月梅花山 2 people like this
  • 2013年淮阴自贡迎春灯会 3 people like this
  • 2012年镇江金山游 1 people like this
  • 2012年徽杭古道 9 people like this
  • 2011年清明节后扬州行 1 people like this
  • 2008年十一云龙公园 5 people like this
  • 2008年之秋忆 7 people like this
  • 老照片 13 people like this
  • 火一样的六月 16 people like this
  • 发黄的相片 3 people like this
  • Cesium学习笔记 90 people like this
  • IntelliJ IDEA知识集锦 59 people like this
  • Bazel学习笔记 38 people like this
  • 基于Kurento搭建WebRTC服务器 38 people like this
  • PhoneGap学习笔记 32 people like this
  • NaCl学习笔记 32 people like this
  • 使用Oracle Java Mission Control监控JVM运行状态 29 people like this
  • Ceph学习笔记 27 people like this
  • 基于Calico的CNI 27 people like this
Tag Cloud
ActiveMQ AspectJ CDT Ceph Chrome CNI Command Cordova Coroutine CXF Cygwin DNS Docker eBPF Eclipse ExtJS F7 FAQ Groovy Hibernate HTTP IntelliJ IO编程 IPVS JacksonJSON JMS JSON JVM K8S kernel LB libvirt Linux知识 Linux编程 LOG Maven MinGW Mock Monitoring Multimedia MVC MySQL netfs Netty Nginx NIO Node.js NoSQL Oracle PDT PHP Redis RPC Scheduler ServiceMesh SNMP Spring SSL svn Tomcat TSDB Ubuntu WebGL WebRTC WebService WebSocket wxWidgets XDebug XML XPath XRM ZooKeeper 亚龙湾 单元测试 学习笔记 实时处理 并发编程 彩姐 性能剖析 性能调优 文本处理 新特性 架构模式 系统编程 网络编程 视频监控 设计模式 远程调试 配置文件 齐塔莉
Recent Comments
  • qg on Istio中的透明代理问题
  • heao on 基于本地gRPC的Go插件系统
  • 黄豆豆 on Ginkgo学习笔记
  • cloud on OpenStack学习笔记
  • 5dragoncon on Cilium学习笔记
  • Archeb on 重温iptables
  • C/C++编程:WebSocketpp(Linux + Clion + boostAsio) – 源码巴士 on 基于C/C++的WebSocket库
  • jerbin on eBPF学习笔记
  • point on Istio中的透明代理问题
  • G on Istio中的透明代理问题
  • 绿色记忆:Go语言单元测试和仿冒 on Ginkgo学习笔记
  • point on Istio中的透明代理问题
  • 【Maven】maven插件开发实战 – IT汇 on Maven插件开发
  • chenlx on eBPF学习笔记
  • Alex on eBPF学习笔记
  • CFC4N on eBPF学习笔记
  • 李运田 on 念爷爷
  • yongman on 记录一次KeyDB缓慢的定位过程
  • Alex on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • haolipeng on 基于本地gRPC的Go插件系统
  • 吴杰 on 基于C/C++的WebSocket库
©2005-2025 Gmem.cc | Powered by WordPress | 京ICP备18007345号-2