regex - 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)
实际上,当没有小写字母时,我的正则表达式会捕获,但我希望它也能在至少有一个大写字母时捕获。
解决方案
您可以使用
^\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
推荐阅读
- r - lm() 与 ifelse() 语句 - R
- laravel - 将 client_secret 放在客户端是否危险?
- java - Java创建目录并删除应该是目录的文件
- python - 推送到 Heroku 时如何解决这个 Flask MySQL 错误?
- llvm - LLVM IR 是否支持(字节 = 16 位)?
- ionic-framework - 在 Ionic 版本 4.10.3 上使用 Ionic Devapp 时出错
- regex - 正则表达式与 Python 3 匹配以下划线开头和结尾的单词
- c# - 删除文本中多行的制表符或空格
- c++ - C++ 计算器类给了我在多个 cpp 文件中分布的最低可能的 int?
- swift - Swift - 在使用 gcd 获得多个网络调用时遇到问题