Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and replace between characters

Tags:

regex

go

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 ANDbetween 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)

like image 286
LaSul Avatar asked Sep 17 '25 08:09

LaSul


1 Answers

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.

like image 166
Wiktor Stribiżew Avatar answered Sep 22 '25 01:09

Wiktor Stribiżew