问题描述
我想检查字符串中每个单词的第一个字符是否为大写。 其他字符应为小写。
例如:
My Lady D'Arbanville => True
My Lady d'arbanville => False
My LADY D'Arbanville => False
我试过:^[A-Z][a-z ']*$
但不工作
解决方法
如果两个大写字符之间可以有一个单引号,您可以选择重复。
^[A-Z](?:'[A-Z])*[a-z]+(?: [A-Z](?:'[A-Z])*[a-z]+)*$
模式匹配:
-
^
字符串开头 -
[A-Z]
匹配 A-Z 范围内的字符 -
(?:'[A-Z])*
可选地重复'
和一个字符 A-Z -
[a-z]+
匹配 a-z 范围内的 1+ 个小写字符 -
(?:
非捕获组作为一个整体重复-
[A-Z]
匹配大写字符 -
(?:'[A-Z])*
(可选)重复'
和大写字符 -
[a-z]+
匹配 a-z 范围内的 1+ 个字符
-
-
)*
可选地重复前面有空格的非捕获组 -
$
字符串结束
也匹配单个大写字符:
^[A-Z](?:'[A-Z])*[a-z]*(?: [A-Z](?:'[A-Z])*[a-z]*)*$
,
对于您显示的示例,请尝试以下正则表达式。
^[A-Z][a-z]+\s+[A-Z][a-z]+\s+[A-Z](?:'[A-Z])?[a-z]+$
说明:为以上添加详细说明。
^[A-Z][a-z]+ ##Checking from starting of value if it starts from capital letter followed by 1 or more small letters here.
\s+ ##Matching 1 or more space occurrences here.
[A-Z][a-z]+ ##Matching 1 occurrence of capital letter followed by 1 or more small letters here.
\s+ ##Matching 1 or more space occurrences here.
[A-Z](?:'[A-Z])? ##Matching single capital letter followed by optional ' capital letter here.
[a-z]+$ ##Matching 1 or more occurrences of small letters till end of value here.
,
我讨厌完全依赖正则表达式,很难隔离边缘情况或缩小一般性。尽管 OP 的问题要求对目标使用正则表达式,但有更简单的方法可以满足此目标并留出适应空间。
下面的函数将传递一个 string
(例如 "My Lady D'Arbanville"
)然后:
-
.split()
通过删除空格 (string
) 或 (array of strings
) 将\s
变成|
单引号 ('
)。`My Lady D'Arbanville`.split(/\s|'/);
返回:
["My","Lady","D","Arbanville"]
-
.every()
word 中的array of strings
将通过function()
进行测试。每个测试的词必须是true
才能将给定的string
报告为true
。["My","Arbanville"].every(function(word) {})
-
function()
将.test()
每个 单词 以查看以下是否为true
:- 第一个字符是大写字母
[A-Z]
- 第一个字符后面的所有字符都是小写的
[a-z]+
或
|
-
\b
word\b
是一个大写字母[A-Z]
/[A-Z][a-z]+|\b[A-Z]\b/.test(word)
- 第一个字符是大写字母
const titleCheck = (text) => {
const wordArray = text.split(/\s|'/);
console.log(wordArray);
return wordArray.every(word => {
const rgx = new RegExp(/[A-Z][a-z]+|\b[A-Z]\b/);
return rgx.test(word);
});
};
/* true
Control
*/
console.log(titleCheck(`My Lady D'Arbanville`));
/* false
A word starting with a lower case letter
*/
console.log(titleCheck(`My Lady D'arbanville`));
/* false
A word with any upper case letter that is
NOT the first letter
*/
console.log(titleCheck(`My LADY D'Arbanville`));
/* false
A single letter word that is lower case
*/
console.log(titleCheck(`My Lady d'Arbanville`));
检查否定条件要简单得多:
\b[a-z]|\B[A-Z]
如果此模式成功,则条件为假。