1

Golang - Match any word except specific

I tried to create a regex which would be able to transform every word to "word" except words: false, true, null, digit

Desired result:

input: type:keyword
output: "type":"keyword"

input: type:keyword,done:true
output: "type":"keyword","done":true

input: type:keyword,done:true,updatedAt:null
output: "type":"keyword","done":true,"updatedAt":null

What I already tried

r := regexp.MustCompile(`(\w+)`)   // get every word, works
r := regexp.MustCompile(`(^true)`) // get everything except "true", doesn't work
r := regexp.MustCompile(`^(true)`) // get everything except "true", doesn't work

I also found this question:

Is there a way to match everything except a constant string using Go.Regexp

but it has 5 years so maybe something has changed.

Updated

this is how I finally solved this issue:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := "type:keyword,done:true,ratio:0.5,stars:4,updated:null"
    r := regexp.MustCompile(`(\w+)`)
    x := r.ReplaceAllString(s, `"$0"`)

    r = regexp.MustCompile(`"(true|false|null|\d)"`)
    x = r.ReplaceAllString(x, `$1`)

    fmt.Println(string(x)) 
    // output:
    // "type":"keyword","done":true,"ratio":0.5,"stars":4,"updated":null
}
mikolaj semeniuk
  • 2,030
  • 15
  • 31

0 Answers0