📜  GO语言 正则表达式(1)

📅  最后修改于: 2023-12-03 15:01:03.512000             🧑  作者: Mango

GO语言 正则表达式

什么是正则表达式?

正则表达式(regular expression,也称作regex、RegExp或RE),是用于匹配字符串中字符组合的模式,在多种程序设计语言中都有实现。

GO语言正则表达式

GO语言内置支持正则表达式,使用正则表达式需要导入regexp包。

GO语言正则表达式函数

GO语言提供了regexp包来支持正则表达式,它提供了一些方法:

| 方法名 | 描述 | | --- | --- | | Match | 匹配 | | MatchReader | 读取匹配 | | MatchString | 字符串匹配 | | QuoteMeta | 转义正则表达式 |

Match

func Match(pattern string, b []byte) (matched bool, err error)

Match方法用来判断正则表达式pattern是否可以匹配b,返回匹配结果matched和错误err。

MatchReader

func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)

MatchReader方法用来判断正则表达式pattern是否可以匹配r中的字符流,返回匹配结果matched和错误err。

MatchString

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

MatchString方法用来判断正则表达式pattern是否可以匹配s,返回匹配结果matched和错误err。

QuoteMeta

func QuoteMeta(s string) string

QuoteMeta方法用来转义正则表达式中的特殊字符,返回转义后的字符串。

正则表达式语法

GO语言支持的正则表达式语法与Perl兼容,并且在Go语法风格上做了一些改进:

字符类

| 类别 | 语法 | 描述 | | --- | --- | --- | | 普通字符 | abc... | 匹配字符abc... | | 转义字符 | \ | 匹配"或\本身 | | 特殊字符 | .[^$(){}+?| | 匹配任意字符、除了^$(){}+?|之外的任何字符、匹配\本身、特殊字符(需要用\转义) | | 字符类 | [abc] / [^abc] | 匹配abc中的任意一个字符、除了abc之外的任意一个字符 | | 范围类 | [a-z]/[^a-z] | 匹配a~z/除了a~z之外的任意一个字符 | | 快捷方式 | \d\D\s\S\w\W | 匹配数字字符/非数字字符/空白字符/非空白字符/单词字符/非单词字符 |

量词

| 语法 | 描述 | | --- | --- | | * | 重复零次或更多次 | | + | 重复一次或更多次 | | ? | 重复零次或一次 | | {n} | 重复n次 | | {n,} | 重复n次或更多次 | | {n,m} | 重复n~m次 |

分组

| 语法 | 描述 | | --- | --- | | (pattern) | 分组捕获,匹配pattern并捕获结果 | | (?:pattern) | 分组不捕获,匹配pattern但不捕获结果 | | (?=pattern) | 正向肯定预查,匹配pattern但不将其作为匹配结果的一部分 | | (?!pattern) | 负向否定预查,不匹配pattern但不将其作为匹配结果的一部分 |

标志位

GO语言的正则表达式标志位通过组合来达到不同的效果,有以下标志位:

| 标志位 | 描述 | | --- | --- | | g | 全局匹配,匹配到一个结果后不会停止 | | i | 忽略大小写 | | m | 多行模式,^$匹配每一行的开头结尾 | | s | 单行模式,.可以匹配换行符 | | U | 非贪婪模式 | | u | 使用Unicode字符集 |

示例
package main

import (
	"fmt"
	"regexp"
)

func main() {
	match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
	fmt.Println(match)

	r, _ := regexp.Compile("p([a-z]+)ch")

	fmt.Println(r.MatchString("peach"))

	fmt.Println(r.FindString("peach punch"))

	fmt.Println(r.FindStringIndex("peach punch"))

	fmt.Println(r.FindStringSubmatch("peach punch"))

	fmt.Println(r.FindStringSubmatchIndex("peach punch"))

	fmt.Println(r.FindAllString("peach punch pinch", -1))

	fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1))

	fmt.Println(r.FindAllString("peach punch pinch", 2))

	fmt.Println(r.Match([]byte("peach")))

	r = regexp.MustCompile("p([a-z]+)ch")
	fmt.Println(r)

	fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))

	in := []byte("a peach")
	out := r.ReplaceAllFunc(in, bytesToUpper)
	fmt.Println(string(out))
}

func bytesToUpper(b []byte) []byte {
	return []byte(strings.ToUpper(string(b)))
}

以上代码示例中使用了常见的正则表达式函数,比如:MatchString、Compile等,同时还展示了正则表达式语法的示例。