I'm trying to replace the second "AND" by "OR" in the following string:
country == "BR" AND (leftHour >= 6 AND rightHour < 24)
My strategy is to do this with regex : \((.*)\)
But this matches all characters between brackets and I just want to match the AND
between the two brackets.
In Go would be perfect, but the good regex could suffice.
Edit : The string is not fixed and we can have multiple "AND" before like, example :
currency == "USD" AND country == "BR" AND (leftHour >= 6 AND rightHour < 24)
You may use a regex like \([^()]*\)
to match strings inside innermost parentheses and use ReplaceAllStringFunc
to only replace all AND
with OR
inside the matched texts:
package main
import (
"fmt"
"strings"
"regexp"
)
func main() {
input := `country == "BR" AND (leftHour >= 6 AND rightHour < 24)`
r := regexp.MustCompile(`\([^()]*\)`)
fmt.Println(r.ReplaceAllStringFunc(input, func(m string) string {
return strings.ReplaceAll(m, "AND", "OR")
}))
}
See the Go demo
Note you may replace AND
using a second regex:
return regexp.MustCompile(`\bAND\b`).ReplaceAllString(m, "OR")
that will replace AND
that are whole words regardless of whether there is a space or not. See this Go demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With