简体   繁体   English

意外的 Go 正则表达式行为

[英]Unexpected Go regex behavior

I have a Go regular expression which is supposed to match a string that starts with a plus-sign followed by 2 to 15 digits:我有一个 Go 正则表达式,它应该匹配一个以加号开头后跟 2 到 15 位数字的字符串:

`\+\d{2,15}`

Testing it like this gives confirms that a string I expect it to match, actually matches:像这样测试它可以确认我希望它匹配的字符串实际上匹配:

regexp.MustCompile(`\+\d{2,15}`).MatchString("+4790") // true, as expected

But when I add a hyphen to the string, I expect it to NOT match.但是当我在字符串中添加连字符时,我希望它不匹配。 However, it still says it matches.但是,它仍然说它匹配。 Why?为什么?

regexp.MustCompile(`\+\d{2,15}`).MatchString("+47-90") // true, should be false?

As the stdlib doc says (italics mine):正如stdlib 文档所说(斜体是我的):

MatchString reports whether the string s contains any match of the regular expression pattern. MatchString 报告字符串 s 是否包含正则表达式模式的任何匹配项。

So if you want the exact match, make the boundaries explicit:因此,如果您想要完全匹配,请明确边界:

regexp.MustCompile(`^\+\d{2,15}$`).MatchString("+47-90")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM