英文:
Go regex string validation
问题
在Go语言中,有一个名为MatchString的函数,可以用于将字符串与正则表达式进行匹配,但是该函数在找到与正则表达式匹配的子字符串时返回true。
是否有一种/类似的函数,只有当整个字符串匹配时才返回true(例如,如果我有[0-9]{2}并且我的字符串是213,则返回值应为false)?还是应该从正则表达式字符串本身来实现这个功能?
英文:
In go there is the function MatchString which can be used to match a string with a regex, however, the function returns true if a substring that matches the regex is found.
Is there a way/similar function that returns true only when the whole of the string is matched (e.g. if I have [0-9]{2} and my string is 213, the return value should be false). ? or should this be done from the regex string itself ?
答案1
得分: 7
尝试这个:
^[0-9]{2}$
GO代码:
package main
import (
"regexp"
"fmt"
)
func main() {
var re = regexp.MustCompile(`(?m)^[0-9]{2}$`)
var str = `213`
for i, match := range re.FindAllString(str, -1) {
fmt.Println(match, "在索引", i, "处找到")
}
}
英文:
Try this:
^[0-9]{2}$
GO CODE:
package main
import (
"regexp"
"fmt"
)
func main() {
var re = regexp.MustCompile(`(?m)^[0-9]{2}$`)
var str = `213`
for i, match := range re.FindAllString(str, -1) {
fmt.Println(match, "found at index", i)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论