I user golang func (*Regexp) Match
to check if a string matches some pattern.
matched = regexp.Match(mystr, []byte(pattern))
How can I write pattern to get matched=true
when passing mystr fulfilling the following requirements:
so mystr="publicfile", "alex/personalfile", "merry/personalfile", "david/personalfile" will get rejected, which means matched=false.
How can I write one patter for this purpose? Thanks in advance.
Here is my approach: I reverse the requirements and obtain either false
or true
:
^(alex|merry|david)|^[^/]+$
The regex will match all strings starting with alex
, merry
or david
OR all strings that do not contain /
, and with !
operator we reverse the Match
result:
var mystr = "alex/personalfile"
var pattern = regexp.MustCompile(`^(alex|merry|david)|^[^/]+$`)
var matched = !pattern.Match([]byte(mystr))
fmt.Println(matched)
Result: false
See IDEONE demo
^(?:(?:alex|merry|david).*|(.*\/.*))$
You can try something like this.This will match all but you need to grab the groups
only.See demo.