gpt4 book ai didi

javascript - 允许使用一个或多个连续大写字母和数字的 PascalCased 的正则表达式

转载 作者:行者123 更新时间:2023-12-03 07:03:08 26 4
gpt4 key购买 nike

我正在尝试检查用户输入的 PascalCased 名称,这很有效,但我还想允许一个或多个连续的大写字母,例如。 UNOrganization 并且还允许介于两者之间的数字,例如。 A2B组织。

因此应允许以下所有内容:ABCWord、A3BWord、OtherWord、Word3、Word3AB(最后不太可能,但如果可能的话很好)

  if (value.match(/^[A-Z][a-z]+(?:[A-Z][a-z]+)*$/)) {
//logic here
}

正则表达式有点超出我的理解范围,解析字符串的逻辑对于我的需要来说太长了,我知道这可以用正则表达式在一行中完成,所以希望更精明的人可以帮助我。

最佳答案

使用

^[A-Z]+[a-z]*(?:\d*(?:[A-Z]+[a-z]*)?)*$

参见 proof

如果您要求输入字符串中至少有一个小写字母:

^(?=.*[a-z])[A-Z]+[a-z]*(?:\d*(?:[A-Z]+[a-z]*)?)*$

解释

--------------------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------------------------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
[a-z] any character of: 'a' to 'z'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
[A-Z]+ any character of: 'A' to 'Z' (1 or more
times (matching the most amount possible))
--------------------------------------------------------------------------------
[a-z]* any character of: 'a' to 'z' (0 or more
times (matching the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
\d* digits (0-9) (0 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[A-Z]+ any character of: 'A' to 'Z' (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
[a-z]* any character of: 'a' to 'z' (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string

关于javascript - 允许使用一个或多个连续大写字母和数字的 PascalCased 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64016829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com