为什么不直接反转与正则表达式^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号.
Update
更多地基于正则表达式并使用the trick的解决方案.
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号.