开发者

Need Regex Pattern: Can't start w num; No special characters except underscore and hyphen; allows characters/nums

开发者 https://www.devze.com 2023-02-06 16:42 出处:网络
Closest I\'ve gotten: ^[-_[a-zA-Z0-9]*$ That still allows the string to start with numbers.Apologies for asking such question when there are resources everywhere.I just need something fast and have p

Closest I've gotten: ^[-_[a-zA-Z0-9]*$

That still allows the string to start with numbers. Apologies for asking such question when there are resources everywhere. I just need something fast and have problems figuring out RegEx.

Valid in开发者_如何转开发put examples: Account-Numbers_2010 | NewMoney | test_data | a1B2-c3_d4_5e-6f

Invalid input examples: 2010_Account_Numbers | New$Money | %test*data | 1aB2


This should make it:

"^[A-Za-z_-][A-Za-z0-9_-]*$"

[A-Za-z_-] means a letter or underscore or hyphen
[A-Za-z0-9_-]* is the same, but allows numbers too

So this will allow letters, underscores, hyphens, and numbers, but no numbers at the start.

Looking at your valid input example Account-Numbers_2010 | NewMoney | test_data | a1B2-c3_d4_5e-6f, you may want to also allow spaces and |. This one allows them:

"^[A-Za-z_ |-][A-Za-z0-9_ |-]*$"

This one correctly matches Account-Numbers_2010 | NewMoney | test_data | a1B2-c3_d4_5e-6f and not 2010_Account_Numbers | New$Money | %test*data | 1aB2.


You need 2 parts to the regex. The first character, and then the rest.

^[a-zA-Z_-][a-zA-Z0-9_-]*$

This says:

Start with any character from a-z or A-Z or _ or -. And then follow that by any alphanumeric character or _ or -.


I hope this helps

^[a-zA-Z]([a-zA-z0-9_-]){0,}
0

精彩评论

暂无评论...
验证码 换一张
取 消