开发者

How can I write a regex to match something which is neither a letter or a digit?

开发者 https://www.devze.com 2023-03-23 11:47 出处:网络
I\'m trying this str = \"bla\"; /([^A-z]|[^0-9])/.tes开发者_StackOverflowt(str.charAt(0)); but it gives me true no matter what I put in the stringIt\'s because your regex means \"anything that is e

I'm trying this

str = "bla";
/([^A-z]|[^0-9])/.tes开发者_StackOverflowt(str.charAt(0));

but it gives me true no matter what I put in the string


It's because your regex means "anything that is either not a letter or not a number." All characters satisfy at least one of those conditions. I suspect what you really want is this:

/[^A-Za-z0-9]/

This means "anything that is both not a letter and not a number." See the difference?

As a side note, [A-z] is incorrect. [A-Z] and [a-z] are two distinct character sets, and there is technically not a defined continuation between them. Some regex engines will let you get away with this, but some will throw an error or do something you didn't intend.

The correct way to write "any letter from A to Z, regardless of case" is [A-Za-z]. Or you could use the i flag to make your regex case-insensitive, which in your case would be:

/[a-z0-9]/i
0

精彩评论

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

关注公众号