[英]Test if string is in Upper Camel Case format with only alphabetic characters
I try to test if the following rules apply on a string: 我尝试测试以下规则是否适用于字符串:
Az
只允许以下字符: Az
For instance, a string can be either String
or CamelCaseString
, but neither string
nor Camel-Case-String
nor String125
. 例如,字符串可以是String
或CamelCaseString
,但既不是string
也不是Camel-Case-String
也不是String125
。 Numerics and special characters must not exist. 数字和特殊字符不得存在。
I found this answer in a previous post. 我在上一篇文章中找到了这个答案 。
const isUpperCamelCase = (str) => {
return /\b[A-Z][a-z]*([A-Z][a-z]*)*\b/.test(str)
}
I have the following test suit that tries to test the above function. 我有以下测试套装试图测试上述功能。 Unfortunately, not all tests pass: 不幸的是,并非所有测试都通过
test('isUpperCamelCase', () => {
expect(isUpperCamelCase('Button')).toBeTruthy()
expect(isUpperCamelCase('GreenButton')).toBeTruthy()
expect(isUpperCamelCase('GreenLargeButton')).toBeTruthy()
expect(isUpperCamelCase('B')).toBeTruthy()
expect(isUpperCamelCase('button')).toBeFalsy()
expect(isUpperCamelCase('buttonCamel')).toBeFalsy()
expect(isUpperCamelCase('Green-Button')).toBeFalsy() // => fail!
expect(isUpperCamelCase('Button125')).toBeFalsy()
expect(isUpperCamelCase('Green_Button')).toBeFalsy()
expect(helpers.isUpperCamelCase('Green+Button')).toBeFalsy() // => fail!
expect(helpers.isUpperCamelCase('green+Button')).toBeFalsy() // => fail!
})
If I include special characters such as (,)+-
in my string the function evaluates to true
when it should evaluate to false
. 如果我在我的字符串中包含特殊字符(如(,)+-
,则该函数在求值为true
时求值为false
。 this happens because there exists a match between the special chars, but this is not the behavior that I want. 发生这种情况是因为特殊字符之间存在匹配,但这不是我想要的行为。 How can I solve this problem? 我怎么解决这个问题?
Note: Please add detail explanation in your answer. 注意:请在答案中添加详细说明。 Thanks! 谢谢! :) :)
You regex needs anchors for matching beginning and ending of the string, not \\b
. 你的正则表达式需要锚点来匹配字符串的开头和结尾,而不是\\b
。 So do: 所以:
/^[A-Z][A-Za-z]*$/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.