How to simulate a negative lookbehind in Go

I am trying to write a regular expression that the command can extract, here is what I have so far used a negative lookbehind statement:

\b(?<![@#\/])\w.*

So, with the input:

/msg @nickname #channel foo bar baz
/foo #channel @nickname foo bar baz 
foo bar baz

foo bar bazretrieved every time. See a working example https://regex101.com/r/lF9aG7/3

In Go, however, this does not compile http://play.golang.org/p/gkkVZgScS_

He throws out:

panic: regexp: Compile(`\b(?<![@#\/])\w.*`): error parsing regexp: invalid or unsupported Perl syntax: `(?<`

I studied a bit and realized that negative lookbehind are not supported in the language to guarantee O (n) time.

How can I rewrite this regex so that it does the same without a negative lookbehind?

+3
source share
2 answers

; :

\b[^@#/]\w.*

, ^:

(?:^|[^@#\/])\b\w.*

Go playground , , , [#@/]. filter:

func Filter(vs []string, f func(string) bool) []string {
    vsf := make([]string, 0)
    for _, v := range vs {
        if f(v) {
            vsf = append(vsf, v)
        }
    }
    return vsf
}

a Process, :

func Process(inp string) string {
    t := strings.Split(inp, " ")
    t = Filter(t, func(x string) bool {
        return strings.Index(x, "#") != 0 &&
            strings.Index(x, "@") != 0 &&
            strings.Index(x, "/") != 0
    })
    return strings.Join(t, " ")
}

http://play.golang.org/p/ntJRNxJTxo

+2

( ) .

Regex

(?:^|[^@#/])\b(\w+)
  • (?:^|[^@#/]) ^ [^@#/] , @#/
  • \b
  • (\w+)
    • \w+

cmds := []string{
    `/msg @nickname #channel foo bar baz`,
    `#channel @nickname foo bar baz /foo`,
    `foo bar baz @nickname #channel`,
    `foo bar baz#channel`}

regex := regexp.MustCompile(`(?:^|[^@#/])\b(\w+)`)


// Loop all cmds
for _, cmd := range cmds{
    // Find all matches and subexpressions
    matches := regex.FindAllStringSubmatch(cmd, -1)

    fmt.Printf("`%v` \t==>\n", cmd)

    // Loop all matches
    for n, match := range matches {
        // match[1] holds the text matched by the first subexpression (1st set of parentheses)
        fmt.Printf("\t%v. `%v`\n", n, match[1])
    }
}

`/msg @nickname #channel foo bar baz`   ==>
    0. `foo`
    1. `bar`
    2. `baz`
`#channel @nickname foo bar baz /foo`   ==>
    0. `foo`
    1. `bar`
    2. `baz`
`foo bar baz @nickname #channel`    ==>
    0. `foo`
    1. `bar`
    2. `baz`
`foo bar baz#channel`   ==>
    0. `foo`
    1. `bar`
    2. `baz`


http://play.golang.org/p/AaX9Cg-7Vx

+1

Source: https://habr.com/ru/post/1614389/


All Articles