gpt4 book ai didi

javascript - 测试字符串是否为仅包含字母字符的大驼峰格式

转载 作者:行者123 更新时间:2023-11-30 11:23:05 27 4
gpt4 key购买 nike

我尝试测试以下规则是否适用于字符串:

  • 必须以大写字母开头。
  • 下一个字符可以是大写或小写格式。
  • 只允许使用以下字符:A-z

例如,字符串可以是StringCamelCaseString,但既不是string 也不是Camel-Case-StringString125。不得存在数字和特殊字符。

我找到了 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/

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