golang regexp.MatchString 出了什么问题?

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

what's wrong with the golang regexp.matchString?

问题

有人能解释一下为什么这个匹配 play 吗?

源码:

package main

import "fmt"
import "regexp"

func main() {
    match, _ := regexp.MatchString("[a-z]+", "test?")
    fmt.Printf("匹配结果:%v", match)
}

难道不是 golang 的 regexp.MatchString 完全匹配吗?我无法理解,我是一个 golang 的新手。

英文:

can any one explain why does this match play?

Source:

package main

import "fmt"
import "regexp"

func main() {
	match, _ := regexp.MatchString("[a-z]+", "test?")
	fmt.Printf("the result of match: %v", match)
}

isn't the golang's regexp.MatchString is fully match? I can't understand and I am a newbie for golang

答案1

得分: 4

正则表达式"[a-z]+"将匹配"test"在搜索文本"test?"中。
同样,它也会匹配"testing testing","2001 a space oddessy"等。

Go语言的regexp包根据正则表达式的语法含义来匹配搜索文本。它没有一个方法本身尝试将正则表达式与整个搜索文本匹配,并在无法匹配时放弃,除非正则表达式定义了整个搜索文本匹配是所需的行为。

正则表达式的语法确实可以匹配整个搜索文本。

'^',即正则表达式开头的锚点符号,强制匹配包括搜索文本的开头。
'$',即正则表达式结尾的锚点符号,强制匹配包括搜索文本的结尾。
它们在正则表达式的其他位置具有不同的含义。

正如@TomCooper评论所说,使用起始和结束锚点将你要查找的正则表达式模式括在其中。这样可以将所包含的正则表达式锚定到搜索文本的开头和结尾,以确保整个搜索文本与正则表达式匹配。

英文:

The regular expression "[a-z]+" will match "test" is the search text "test?".
Similarly, it will match "testing testing", "2001 a space oddessy", etc.

Go lang's regexp package matches search text according to the syntax and meaning of the regular expression. There isn't a method which itself tries to match the regular expression with the entire search text, and gives up if it can't, unless the regular expression defines that an entire search-text-match is the required behaviour.

The syntax of regular expressions does enable matching the entire search text.

'^', the start-anchor symbol at the start of the regular expression forces the match to include the start of the search text.
'$', the end-anchor symbol at the end of the regular expression forces the match to include the end of the search text.
They have different meaning in other positions within a regular expression.

As @TomCooper commented, use both start and end anchors around the regular expression pattern you are looking for. These anchor the enclosed regular expression to the start and end of the search text to ensure the entire search text matches the regular expression.

huangapple
  • 本文由 发表于 2015年11月18日 20:51:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/33780595.html
匿名

发表评论

匿名网友

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

确定