In Go, utilizing the regular expression engine RE2, there is no direct way to employ lookahead assertions to match all characters except a specific string. However, there are alternative approaches to achieve this functionality:
Web Service to Generate Negated Patterns
For example, if the generated negated pattern is:
[^([^s]|s(s|o(s|m(s|es(omes)*(s|t(s|r(s|i(s|ns)))|o(s|ms)))))*([^os]|o([^ms]|m([^es]|e([^s]|s(omes)*([^ost]|t([^rs]|r([^is]|i([^ns]|n[^gs])))|o([^ms]|m([^es]|e[^s]))))))))*(s(s|o(s|m(s|es(omes)*(s|t(s|r(s|i(s|ns)))|o(s|ms)))))*(o((me?)?|mes(omes)*(t(r?|rin?)|o(me?)?)?))?)?$
Your final regex will look like:
/[^/]*/[^/]*/(([^s]|s(s|o(s|m(s|es(omes)*(s|t(s|r(s|i(s|ns)))|o(s|ms)))))*([^os]|o([^ms]|m([^es]|e([^s]|s(omes)*([^ost]|t([^rs]|r([^is]|i([^ns]|n[^gs])))|o([^ms]|m([^es]|e[^s]))))))))*(s(s|o(s|m(s|es(omes)*(s|t(s|r(s|i(s|ns)))|o(s|ms)))))*(o((me?)?|mes(omes)*(t(r?|rin?)|o(me?)?)?))?)?)$
Capturing All Parts
Alternatively, you can capture all three parts of the input string (separated by forward slashes) into a slice. Then, check if the third part (val[1]) equals the string you want to exclude ("somestring" in this case). If it does not match, use val[1] as the expected result:
package main import ( "fmt" "regexp" ) func main() { s := "anything/anything/somestring" r := regexp.MustCompile(`^[^/]+/[^/]+/(.*)`) val := r.FindStringSubmatch(s) // fmt.Println(val[1]) // -> somestring if len(val) > 1 && val[1] != "somestring" { // val has more than 1 element and is not equal to somestring? fmt.Println(val[1]) // Use val[1] } else { fmt.Println("No match") // Else, report no match } }
The above is the detailed content of How to Exclude a Specific String When Matching in Go Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!