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

WBOY
Release: 2024-02-08 20:51:04
forward
1103 people have browsed it

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)
    }
  }
}
Copy after login

Output:

<code>FooA
FooB
FooBa
FooBax
FooBxr
FooBarAbc
FooBarFoo
</code>
Copy after login

Try it on rextester.

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

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])
    }
  }
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template