I'm trying to find a way to match a pattern with regexp.Regexp
using Go.
The standards of the competition are as follows:
FooBar
or its substring Foo
at the beginning of the line, or not match at all. \S
) So, it should match, for example:
FooABC
FooBarABC
FooBar
(because there are no other characters after it) 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.
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!