Home >Backend Development >Golang >How Can I Effectively Perform Negative Matching in Go Regular Expressions Without Lookarounds?

How Can I Effectively Perform Negative Matching in Go Regular Expressions Without Lookarounds?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 12:39:09590browse

How Can I Effectively Perform Negative Matching in Go Regular Expressions Without Lookarounds?

Negative Matching in Go Regex

In Go regexp, matching everything except a specific constant string can be challenging due to the lack of lookaround constructs.

Original RegExp:

The provided regular expression, /.*/.*/(.*), matches everything after three backslashes. However, it does not exclude strings containing "somestring".

Negation Approaches

Method 1: Web Service

One workaround involves using a web service that generates POSIX-compatible negated patterns. For "somestring", this generates a complex pattern that can be substituted into the original RegExp:

/[^/]*/[^/]*/^([^s]|s(s|o(s|m(s|es(omes)*(s|t(s|r(s|i(s|ns)))|o(s|ms)))))*([^os]|o([^ms]|m([^es]|e([^s]|s(omes)*([^ost]|t([^rs]|r([^is]|i([^ns]|n[^gs])))|o([^ms]|m([^es]|e[^s]))))))))*(s(s|o(s|m(s|es(omes)*(s|t(s|r(s|i(s|ns)))|o(s|ms)))))*(o((me?)?|mes(omes)*(t(r?|rin?)|o(me?)?)?))?)?$

Method 2: Character Class

Instead of using .*, the following expression uses a negated character class [^/]:

`[^/]+/[^/]+/(.*)`

This matches anything up to the third backslash, but it does not exclude strings with "somestring".

Workaround using Capture Groups

Since RE2 (which Go uses) does not support lookaheads, we can capture all three parts of the string and check the extracted value of the capture group:

import (
    "fmt"
    "regexp"
)

func main() {
    s := "anything/anything/somestring"
    r := regexp.MustCompile(`^[^/]+/[^/]+/(.*)`)
    val := r.FindStringSubmatch(s)
    if len(val) > 1 && val[1] != "somestring" {
        fmt.Println(val[1])
    } else {
        fmt.Println("No match")
    }
}

This approach captures the matched values and prints them if they do not match "somestring".

The above is the detailed content of How Can I Effectively Perform Negative Matching in Go Regular Expressions Without Lookarounds?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn