作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试测试以下规则是否适用于字符串:
A-z
例如,字符串可以是String
或CamelCaseString
,但既不是string
也不是Camel-Case-String
或 String125
。不得存在数字和特殊字符。
我找到了 this answer在之前的帖子中。
const isUpperCamelCase = (str) => {
return /\b[A-Z][a-z]*([A-Z][a-z]*)*\b/.test(str)
}
我有以下测试服试图测试上述功能。不幸的是,并非所有测试都通过:
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!
})
如果我在我的字符串中包含特殊字符,例如 (,)+-
,则该函数在应计算为 false
时计算为 true
.发生这种情况是因为特殊字符之间存在匹配,但这不是我想要的行为。我怎么解决这个问题?
注意:请在您的回答中添加详细说明。谢谢! :)
最佳答案
您的正则表达式需要 anchor 来匹配字符串的开头和结尾,而不是 \b
。也是如此:
/^[A-Z][A-Za-z]*$/
关于javascript - 测试字符串是否为仅包含字母字符的大驼峰格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49077460/
如 this question适用于“大型”Visual Studio 和 Resharper,我也希望在 VS Code 中看到该功能。 滚动浏览 shortcut list对于 VS Code,我
我是一名优秀的程序员,十分优秀!