【问题标题】:regex in go that match with no lowercase and at least one uppercase?go 中的正则表达式匹配没有小写字母和至少一个大写字母?
【发布时间】:2019-11-09 09:35:33
【问题描述】:

当没有小写字母且至少有一个大写字母时,我需要在 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)

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

【问题讨论】:

  • 查看golang.org/pkg/regexp/syntax 并使用例如\p{Lu}Ll(最接近您的要求)。
  • 我已经有了,但我认为我只是在使用正则表达式。无论如何,Wiktor Stribiżew 的回答对我有用。
  • 实际上,我对这个问题的投票数感到非常惊讶:问题已明确说明,有一个有效的尝试来解释它有什么问题,并且有预期结果的示例字符串。

标签: regex go regex-lookarounds


【解决方案1】:

你可以使用

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

或者,更高效一点:

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

请参阅regex demo

详情

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

Go test:

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

【讨论】:

  • 我确信 Δ 和 Γ 是大写字母,而 ε 和 ρ 是小写字母,它们都不适用于您的解决方案。
  • @Volker 好的,我添加了另一个测试,fmt.Println(re.MatchString(Δ != Γ)) 返回 true。
猜你喜欢
  • 1970-01-01
  • 2016-12-14
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
相关资源
最近更新 更多