Unknown escape at negated match in reqex

I want to check the string between {} in my statement, in JavaScript I can use:
Negative Lookahead to matches characters of the A to Z range as [a-zA-Z]+(?![^{]*\})
Or Negated Match if words will include whitespace or have other characters that need to be allowed or unsure of the type of input as [^}]+(?![^{]*\})

Here is a live example to check the below text

{con}descens{ion}
lumberjack
tim{ing}
{tox}{icity}
fish
{dis}pel

I tried to do same in GO as;

package main

import (
	"fmt"
	"regexp"
)

func main() {
	r, err := regexp.Compile('[a-zA-Z]+(?![^{]*\})')
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.ReplaceAllString(`{con}descens{ion}
									lumberjack
									tim{ing}
									{tox}{icity}
									fish
									{dis}pel`,
									"found this"))
}

But got the below error:

# command-line-arguments
.\reg.go:9:46: unknown escape

I used below to get everything between {} , is there a way to reverse it, i.e. select characters not match with this selection?

re := regexp.MustCompile("{([^{}]*)}")        // start by {, end by }, contains any character except { and }  [^{}]

You must use the double quote " to enclose strings. And escaping the } as \{ is not correct. Write this:

regexp.Compile("[a-zA-Z]+(?![^{]*})")

But Go does not support perl syntax. Running the above gives this error:

error parsing regexp: invalid or unsupported Perl syntax: (?!

I am not a regex guru so I don’t know what to do now.

Go does not support look ahead / look behind. The reason is, is that the searches can take a very long (exponential) time.

However you can do something like this

func main() {
	r, err := regexp.Compile(`\s*(\{.*?\}|\n)\s*`)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("result = %q\n",
		r.Split(`{con}descens{ion}
			lumberjack
			tim{ing}
			{tox}{icity}
			fish
			{dis}pel`,
			-1))
}

Playground

PS this is because you need to put your regexp in backquotes `

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.