小白学正则表达式之 regexp


1. 正则表达式介绍

正则表达式是程序文本处理常用的模板模式,按照解析正则表达式的引擎可将正则表达式分为 POSIX 基础正则表达式(Basic regular expression,BRE) 引擎和 POSIX 扩展正则表达式(extended regular expression,ERE) 引擎。

2. BRE 引擎

2.1 纯文本匹配和特殊字符

正则表达式中特殊字符转换为文本需要加反斜杠 \。

2.2 锚字符

锚字符可以锁定数据流的行首和行尾。其中,脱字符 ^ 锁定行首,美元符 $ 锁定行尾。

2.3 点号字符

点号字符匹配数据流中的任意单个字符。

2.4 字符组

字符组使用 [ ] 表示,匹配文本模式中某个位置的一组字符。如 [Yy] 匹配数据流中包含 Y 或 y 的任意单个字符。

2.4.1 区间

区间使用 - 表示,如 [a-z] 匹配数据流中包括从 a 到 z 之间任意单个字符。

2.4.2 排除型字符组

排除型字符组在字符前加脱字符用于排除匹配的字符组。如 [^a-z] 匹配不属于 a 到 z 之间的数据流。

2.5 星号

在字符/字符组后加星号,表示该字符可出现 0 次或多次。如 [a-z]*表明数据流中 a 到 z 的字符可出现 0 次到多次。

3. ERE 引擎

3.1 问号

问号类似于星号,表示字符可出现 0 次或 1 次。

4. Go 正则表达式 regexp 包

4.1 MatchString

//MatchString reports whether the string s contains any match of the regular expression pattern. More complicated queries need 
//to use Compile and the full Regexp interface.

func MatchString(pattern string, s string) (matched bool, err error)

4.2 MustCompile

//MustCompile is like Compile but panics if the expression cannot be parsed. It simplifies safe initialization of global 
//variables holding compiled regular expressions.

func MustCompile(str string) *Regexp

4.3 FindString

func (re *Regexp) FindString(s string) string

example:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`foo.?`)
	fmt.Printf("%q\n", re.FindString("seafood fool"))
	fmt.Printf("%q\n", re.FindString("meat"))
}

结合 MustCompile 和 FindString 的示例:

status := regexp.MustCompile(string(ProcessRegexPattern)).FindString(string(status))

芝兰生于空谷,不以无人而不芳。
原文地址:https://www.cnblogs.com/xingzheanan/p/15645086.html