Regex:验证字符串为字母大写或大写蛇形大小写



我需要创建一个regex来验证字符串只接受字母大写或大写蛇形大小写:

有效:

HELLO
HELLO_WORLD
HELLO_WORLD_HELLO_WORLD

无效:

123
___
HELLO WORLD
hello_world
HELLO_WORLD HELLO

我创建这个是为了接受大写字母蛇的大小写:

^[A-Z]+(_[A-Z]+)

但是我也需要允许一个字的字符串

使用您所展示的示例,请尝试以下操作。

^[A-Z]+(?:_[A-Z]+)*$

以上代码的在线正则表达式

解释:

^[A-Z]+    ##Simply checking if value starting from capital letters A to Z with 1 or more occurrences.
(?:        ##Starting a non capturing group here.
_[A-Z]+    ##Mentioning _ and one or more occurrences of A to Z here.
)*         ##Closing non capturing group here with * to look for one or more occurrences.
$          ##Till end of the value.
^[A-Z]+(?:[_][A-Z]+)*$

结果:

AAAA - yes
AAAa - no
aaa - no
aaa_ - no
aaa_a - no
aAa_a - no
AAAA_B - yes

最新更新