Go中字符串末尾的正则表达式匹配失败
Fail the regex match at the end of the string in Go
我正在尝试根据此模式测试字符串:"At least one square bracket pair, wrapping 2 digits, followed by at lease one character"。例如,[11][22][33]dd
应该匹配,而 [11][22][33]
不应该匹配。
我试过这个正则表达式:(\[\d{2}])+.+
。然而,当它用 [11][22][33]
进行测试时,它应该会失败,但它仍然通过了该测试。第一个 +
量词只匹配两个组 [11]
和 [22]
,而其余部分 [33]
被 .+
.
匹配
我认为 +
量词的 "greedy" 行为会耗尽它修改的组的所有匹配段;然而,正则表达式引擎似乎会将 "exhaust all matching possibilities" 原则置于 "greedy quantifier" 规则之上,而不是我预期的方式。
我应该如何实现我的目标?
(这个问题实际上与语言无关,尽管用 "golang" 标记,这是我当前使用的语言。)
我想您需要使用的正则表达式是这样的:
(\[[0-9]{2}\]){1,}[a-z]{1,}
您可以使用
re := regexp.MustCompile(`(?:\[\d{2}])+(.*)`)
match := re.FindStringSubmatch(s)
if len(match) > 1 {
return match[1] != ""
}
return false
(?:\[\d{2}])+(.*)
模式匹配 1+ 次出现的 [
、2 位数字、]
,然后将换行符以外的任何 0 个或更多字符捕获到组 1 中。然后,如果找到匹配项 (if len(match) > 1
),如果第 1 组值不为空 (match[1] != ""
),则应返回 true
,否则返回 false
。
参见Go demo:
package main
import (
"fmt"
"regexp"
)
func main() {
strs := []string{
"[11][22][33]",
"___[11][22][33]",
"[11][22][33]____",
"[11][22]____[33]",
}
for _, str := range strs {
fmt.Printf("%q - %t\n", str, match(str))
}
}
var re = regexp.MustCompile(`(?:\[\d{2}])+(.*)`)
func match(s string) bool {
match := re.FindStringSubmatch(s)
if len(match) > 1 {
return match[1] != ""
}
return false
}
输出:
"[11][22][33]" - false
"___[11][22][33]" - false
"[11][22][33]____" - true
"[11][22]____[33]" - true
我正在尝试根据此模式测试字符串:"At least one square bracket pair, wrapping 2 digits, followed by at lease one character"。例如,[11][22][33]dd
应该匹配,而 [11][22][33]
不应该匹配。
我试过这个正则表达式:(\[\d{2}])+.+
。然而,当它用 [11][22][33]
进行测试时,它应该会失败,但它仍然通过了该测试。第一个 +
量词只匹配两个组 [11]
和 [22]
,而其余部分 [33]
被 .+
.
我认为 +
量词的 "greedy" 行为会耗尽它修改的组的所有匹配段;然而,正则表达式引擎似乎会将 "exhaust all matching possibilities" 原则置于 "greedy quantifier" 规则之上,而不是我预期的方式。
我应该如何实现我的目标?
(这个问题实际上与语言无关,尽管用 "golang" 标记,这是我当前使用的语言。)
我想您需要使用的正则表达式是这样的:
(\[[0-9]{2}\]){1,}[a-z]{1,}
您可以使用
re := regexp.MustCompile(`(?:\[\d{2}])+(.*)`)
match := re.FindStringSubmatch(s)
if len(match) > 1 {
return match[1] != ""
}
return false
(?:\[\d{2}])+(.*)
模式匹配 1+ 次出现的 [
、2 位数字、]
,然后将换行符以外的任何 0 个或更多字符捕获到组 1 中。然后,如果找到匹配项 (if len(match) > 1
),如果第 1 组值不为空 (match[1] != ""
),则应返回 true
,否则返回 false
。
参见Go demo:
package main
import (
"fmt"
"regexp"
)
func main() {
strs := []string{
"[11][22][33]",
"___[11][22][33]",
"[11][22][33]____",
"[11][22]____[33]",
}
for _, str := range strs {
fmt.Printf("%q - %t\n", str, match(str))
}
}
var re = regexp.MustCompile(`(?:\[\d{2}])+(.*)`)
func match(s string) bool {
match := re.FindStringSubmatch(s)
if len(match) > 1 {
return match[1] != ""
}
return false
}
输出:
"[11][22][33]" - false
"___[11][22][33]" - false
"[11][22][33]____" - true
"[11][22]____[33]" - true