英文:
How to write regex pattern for the following string to be matched
问题
我使用golang的func (*Regexp) Match
来检查字符串是否与某个模式匹配。
matched = regexp.Match(mystr, []byte(pattern))
当传递满足以下要求的mystr时,如何编写模式以获得matched=true
:
- 至少包含一个"/"
- 不以"alex/"、"merry/"、"david/"开头
因此,mystr="publicfile"、"alex/personalfile"、"merry/personalfile"、"david/personalfile"将被拒绝,即matched=false。
如何编写一个模式来实现这个目的?提前感谢。
英文:
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:
- contain at least one "/"
- not start with "alex/", "merry/", "david/"
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.
答案1
得分: 1
这是我的方法:我反转了要求,并得到了false
或true
:
^(alex|merry|david)|^[^/]+$
这个正则表达式将匹配以alex
、merry
或david
开头的所有字符串,或者不包含/
的所有字符串,并且使用!
运算符来反转Match
的结果:
var mystr = "alex/personalfile"
var pattern = regexp.MustCompile(`^(alex|merry|david)|^[^/]+$`)
var matched = !pattern.Match([]byte(mystr))
fmt.Println(matched)
结果:false
参见IDEONE演示
英文:
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
答案2
得分: 0
你可以尝试这样的表达式。它将匹配所有内容,但你只需要获取“groups”部分。请参考演示。
https://regex101.com/r/fM9lY3/27
英文:
^(?:(?:alex|merry|david).*|(.*\/.*))$
You can try something like this.This will match all but you need to grab the groups
only.See demo.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论