Home  >  Article  >  Backend Development  >  Go Regexp: Match full word or substring or not at all

Go Regexp: Match full word or substring or not at all

WBOY
WBOYforward
2024-02-08 20:51:041048browse

Go Regexp:匹配完整单词或子字符串或根本不匹配

Question content

I'm trying to find a way to match a pattern with regexp.Regexp using Go.

The standards of the competition are as follows:

  1. It must match FooBar or its substring Foo at the beginning of the line, or not match at all.
  2. If matched in #1, any match must be followed by other characters (i.e. \S )

So, it should match, for example:

  • Matches: FooABC
  • Matches: FooBarABC
  • Does not match: FooBar (because there are no other characters after it)
  • Does not match: ABC (because it does not start with Foo)

I've tried various expressions but can't seem to understand it.

I've found that negative lookahead mode exists in other implementations, but Go doesn't seem to provide it. Is there any other way to solve this problem?

See (updated): https://regex101.com/r/SWSTzv/3

I know this can obviously be solved without using regexp. However, the purpose of this request is to understand whether this problem can be solved by Go's stdlib implementation.


Correct answer


Why not just reverse the result that matches the regular expression ^Foo(?:Bar)?$ (ok , not just)?

package main

import (
  "fmt"
  "regexp"
  "strings"
)

func main() {
  re := regexp.MustCompile(`^Foo(?:Bar)?$`)
  str := `Foo
FooBar
FooA
FooB
FooBa
FooBax
FooBxr
FooBarAbc
FooBarFoo
ABC
AbcFooBar`

  for _, s := range strings.Split(str, "\n") {
    if strings.HasPrefix(s, "Foo") && !re.MatchString(s) {
      fmt.Println(s)
    }
  }
}

Output:

<code>FooA
FooB
FooBa
FooBax
FooBxr
FooBarAbc
FooBarFoo
</code>

Try it on rextester.

renew
One that is more regular expression based and uses tips em>.

package main

import (
  "fmt"
  "regexp"
  "strings"
)

func main() {
  re := regexp.MustCompile(`^Foo$|^FooBar$|^(Foo.+)`)
  str := `Foo
FooBar
FooA
FooB
FooBa
FooBax
FooBxr
FooBarAbc
FooBarFoo
ABC
AbcFooBar`

  for _, s := range strings.Split(str, "\n") {
    submatches := re.FindStringSubmatch(s)
    if submatches != nil && submatches[1] != "" {
      fmt.Println(submatches[1])
    }
  }
}

Try it on rextester.

The above is the detailed content of Go Regexp: Match full word or substring or not at all. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete