正则表达式规则内容较多,此处仅介绍提取()``{}子表达式的内容,并介绍涉及的规则。
提取子表达式的内容
提取子表达式()中的内容
待匹配文本:"foo(bar)foo(baz)golang"
提取规则:(([^)] ))
提取结果:(bar) (baz)
测试网址:https://tool.oschina.net/regex/
提取子表达式{}中的内容
待匹配文本:"Say {goodbye to complex processes}. Participate in promising {lending and decentralized } projects"
提取规则:{([^}] )}
提取结果:{goodbye to complex processes} {lending and decentralized }
测试网址:https://tool.oschina.net/regex/
规则介绍
(: 匹配表达式中的(,其中为转义标示,因为(为特殊字符,匹配(需要进行转义{: 同理该表达式为匹配表达式中的{
([^)] ): 一个捕获组()表示子表达的开始和结束,它内部包含一个子表达式的匹配规则[^) ]: 一次或多次与非)右括号匹配,在[]中使用^表示非、排除的意思
: 匹配前面的表达式一次或多次}: 匹配表达式中的}^: 除了在[]中使用时表示非、排除的意思外,其它情况表示匹配字符串的起始位置$: 匹配字符串的结束位置^a{1,3}$: 近当字符串为1、2、3个a时才匹配.
golang 代码示例
代码语言:go复制package main
import (
"fmt"
"regexp"
)
func main(t *testing.T) {
str := "Say {goodbye to complex processes}. Participate in promising {lending and exchange} projects"
rex := regexp.MustCompile(`({([^}] )})([^{^}])`)
fmt.Printf("% vn", rex.FindAllString(str, -1))
}


