首页 > 解决方案 > go 中的正则表达式匹配没有小写字母和至少一个大写字母?

问题描述

当没有小写字母且至少有一个大写字母时,我需要在匹配中找到一个正则表达式。

例如:

"1 2 3 A"  : Match
"1 2 3"    : No match
"a A "     : no match
"AHKHGJHB" : Match

这项工作但在 PHP 中不在 Go 中(?=令牌在 Go 中不起作用):

(?=.*[A-Z].*)(?=^[^a-z]*$)

在我的代码中,这一行调用了正则表达式:

isUppcase, _ := reg.MatchString(`^[^a-z]*$`, string)

实际上,当没有小写字母时,我的正则表达式会捕获,但我希望它也能在至少有一个大写字母时捕获。

标签: regexgoregex-lookarounds

解决方案


您可以使用

^\P{Ll}*\p{Lu}\P{Ll}*$

或者,更高效一点:

^\P{L}*\p{Lu}\P{Ll}*$

请参阅正则表达式演示

细节

  • ^- 字符串的开始
  • ^\P{L}*- 0个或更多字符而不是字母
  • \p{Lu}- 一个大写字母
  • \P{Ll}*- 0 个或多个小写字母以外的字符
  • $- 字符串结束。

去测试

package main

import (
    "regexp"
    "fmt"
)

func main() {
    re := regexp.MustCompile(`^\P{L}*\p{Lu}\P{Ll}*$`)
    fmt.Println(re.MatchString(`1 2 3 A`))   
    fmt.Println(re.MatchString(`1 2 3`))   
    fmt.Println(re.MatchString(`a A`))   
    fmt.Println(re.MatchString(`AHKHGJHB`))   
    fmt.Println(re.MatchString(`Δ != Γ`)) 
}

输出:

true
false
false
true
true

推荐阅读