Home >Backend Development >Golang >How to Exclude Specific Strings When Using Go Regex?

How to Exclude Specific Strings When Using Go Regex?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 08:57:24170browse

How to Exclude Specific Strings When Using Go Regex?

Go Regex: Exccluding Specific Strings

In Go, you may encounter challenges when attempting to match anything except certain constant strings using the regexp package. While many suggested solutions involving lookaheads are not applicable due to Go regexp's limited syntax, alternative approaches are available.

Workaround 1: Use a Negated Pattern Generator

Since Go regexp does not support lookaheads, consider using an external service like http://www.formauri.es/personal/pgimeno/misc/non-match-regex to generate negated patterns. For example, the negated pattern for "somestring" is:

$ ^([^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?)?)?))?)?$

To use this negated pattern in your original regex, replace the last (.*) with the , resulting in a pattern that looks like:

/[^/]*/[^/]*/(([^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?)?)?))?)?)$

Alternatively, you can use the [^/] pattern to match zero or more characters other than / instead of .*.

Workaround 2: Capture All Sections and Check Values

Although you cannot use lookaheads, you can capture all three parts of your pattern and check the value of the first capture group to determine whether to use the captured value or report no match:

package main

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")
    }
}

The above is the detailed content of How to Exclude Specific Strings When Using Go Regex?. 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