我正在尝试找到一种使用 Go 将模式与 regexp.Regexp 进行匹配的方法。
比赛的标准如下:
所以,它应该匹配,例如:
我尝试了各种表达方式,但似乎无法理解它。
我发现其他实现中存在负向先行模式,但Go似乎没有提供它。有没有其他方法可以解决这个问题?
参见(已更新):https://regex101.com/r/SWSTzv/3
我知道这显然可以在不使用 regexp 的情况下解决。然而,这个请求的目的是了解这个问题是否可以通过 Go 的 stdlib 实现来解决。
为什么不直接反转与正则表达式 ^Foo(?:Bar)?$ 匹配的结果(好吧,不只是)?
package main import ( "fmt" "regexp" "strings" ) func main() { re := regexp.MustCompile(`^Foo(?:Bar)?$`) str := `Foo FooBar FooA FooB FooBa FooBax FooBxr FooBarAbc FooBarFoo ABC AbcFooBar` for _, s := range strings.Split(str, "\n") { if strings.HasPrefix(s, "Foo") && !re.MatchString(s) { fmt.Println(s) } } }
输出:
FooA FooB FooBa FooBax FooBxr FooBarAbc FooBarFoo
在 rextester 上尝试一下。
更新
一种更基于正则表达式并使用技巧 em>.
package main import ( "fmt" "regexp" "strings" ) func main() { re := regexp.MustCompile(`^Foo$|^FooBar$|^(Foo.+)`) str := `Foo FooBar FooA FooB FooBa FooBax FooBxr FooBarAbc FooBarFoo ABC AbcFooBar` for _, s := range strings.Split(str, "\n") { submatches := re.FindStringSubmatch(s) if submatches != nil && submatches[1] != "" { fmt.Println(submatches[1]) } } }
在 rextester 上尝试一下。
以上就是Go Regexp:匹配完整单词或子字符串或根本不匹配的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号