我有一个字符串
centenary
我ten只想在没有前面的时候匹配cen.
到目前为止,我有这个正则表达式:
(([^c][^e][^n])|^)ten
返回true在下列情况下tenary,blahtenary假的ctenary,cetenary,centanary
package main
import (
"fmt"
"regexp"
)
func main() {
txt := "ctenary"
rx := `(([^c][^e][^n])|^)ten`
re := regexp.MustCompile(rx)
m := re.MatchString(txt)
fmt.Println(m)
}
Run Code Online (Sandbox Code Playgroud)
由于缺少对前瞻或后瞻的支持,我们需要坚持否定的字符类 - 但[^c][^e][^n]不完全覆盖它,因为它不允许cxxten而且也不包括之前没有3个字符的字符串ten.
我提出了(?:^|[^n]|(?:[^e]|^)n|(?:[^c]|^)en)ten,存储ten到第一个被捕获的组.它为每种可能的方式创造了不完全匹配的替代方案cen.
(.{0,3})(ten)如果第一组存储,则替代方案可能是以编程方式匹配和丢弃匹配cen.