内容简介:总是有一些任务,例如输入验证,在文档中搜索任何信息,甚至从不需要的转义字符中清除给定的字符串。对于这些情况,通常可以使用正则表达式。
总是有一些任务,例如输入验证,在文档中搜索任何信息,甚至从不需要的转义字符中清除给定的字符串。对于这些情况,通常可以使用正则表达式。
通过正则表达式模式查找文本中的子字符串
Golang 版本
1.12.1
前言
总是有一些任务,例如输入验证,在文档中搜索任何信息,甚至从不需要的转义字符中清除给定的字符串。对于这些情况,通常可以使用正则表达式。
实现
package main
import (
"fmt"
"regexp"
)
const refString = `[{ \"email\": \"email@example.com\" \
"phone\": 555467890},
{ \"email\": \"other@domain.com\" \
"phone\": 555467890}]`
func main() {
// 为简洁起见,简化了这种模式
emailRegexp := regexp.MustCompile("[a-zA-Z0-9]{1,}@[a-zA-Z0-9]{1,}\\.[a-z]{1,}")
first := emailRegexp.FindString(refString)
fmt.Println("First: ")
fmt.Println(first)
all := emailRegexp.FindAllString(refString, -1)
fmt.Println("All: ")
for _, val := range all {
fmt.Println(val)
}
}
$ go run regexp.go First: email@example.com All: email@example.com other@domain.com
原理
FindString
或 FindAllString
函数是查找给定字符串中匹配模式的最简单方法。唯一的区别是 Regexp
的 FindString
方法只返回首个。另一方面, FindAllString
,顾名思义,返回所有出现的字符串片段。
Regexp
类型提供了一组丰富的 FindXXX
方法。本篇只描述通常最有用的字符串变体。注意,前面的代码使用 regexp
包的 MustCompile
函数,如果正则表达式的编译失败,该函数将引发恐慌。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Ordering Disorder
Khoi Vinh / New Riders Press / 2010-12-03 / USD 29.99
The grid has long been an invaluable tool for creating order out of chaos for designers of all kinds—from city planners to architects to typesetters and graphic artists. In recent years, web designers......一起来看看 《Ordering Disorder》 这本书的介绍吧!