如何编写正则表达式模式以匹配以下字符串

huangapple go评论80阅读模式
英文:

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

这是我的方法:我反转了要求,并得到了falsetrue

^(alex|merry|david)|^[^/]+$

这个正则表达式将匹配以alexmerrydavid开头的所有字符串,或者不包含/的所有字符串,并且使用!运算符来反转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.

https://regex101.com/r/fM9lY3/27

huangapple
  • 本文由 发表于 2015年8月10日 17:06:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/31915595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定