Home >Backend Development >Golang >How Can I Emulate Negative Lookbehinds in Go Regular Expressions?
While Go doesn't natively support negative lookbehinds in regular expressions for performance reasons, an alternative strategy can be employed to achieve similar functionality.
Consider the original regex:
\b(?<p>Since the negated lookbehind only examines a character set, it can be replaced with a negated character set itself:</p><pre class="brush:php;toolbar:false">\b[^@#/]\w.*
If characters may appear at the beginning of the string, add the ^ anchor:
(?:^|[^@#\/])\b\w.*
For a more refined approach, a filter function can be implemented:
func Filter(vs []string, f func(string) bool) []string { vsf := make([]string, 0) for _, v := range vs { if f(v) { vsf = append(vsf, v) } } return vsf }
This filter function can then be employed in a Process function:
func Process(inp string) string { t := strings.Split(inp, " ") t = Filter(t, func(x string) bool { return strings.Index(x, "#") != 0 && strings.Index(x, "@") != 0 && strings.Index(x, "/") != 0 }) return strings.Join(t, " ") }
Overall, these techniques enable the emulation of negative lookbehinds in Go, providing a workaround for the lack of direct language support for this feature.
The above is the detailed content of How Can I Emulate Negative Lookbehinds in Go Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!