Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the regular expression [a-Z] valid and if yes then is it the same as [a-zA-Z]?

Tags:

regex

Is the regular expression [a-Z] valid and if yes then is it the same as [a-zA-Z]? Please note that in [a-Z] the a is lowercase and the Z is uppercase.

Edit:

I received some answers specifiying that while [a-Z] is not valid then [A-z] is valid (but won't be the same as [a-zA-Z]) and this is really what I was looking for. Since I wanted to know in general if it's possible to replace [a-zA-Z] with a more compact version.

Thanks for all who contributed to the answer.

like image 539
Karim Avatar asked Nov 01 '09 23:11

Karim


People also ask

Is AZ same as a zA Z?

[A-z] will match ASCII characters in the range from A to z , while [a-zA-Z] will match ASCII characters in the range from A to Z and in the range from a to z . At first glance, this might seem equivalent -- however, if you look at this table of ASCII characters, you'll see that A-z includes several other characters.

What does a zA z mean in regex?

Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.

What does the regular expression A to Z match?

The regular expression [A-Z][a-z]* matches any sequence of letters that starts with an uppercase letter and is followed by zero or more lowercase letters.

Is AZ a valid regex?

Given that this has taken quite some time to debug, I strongly discourage anyone from ever using [a-Z] in a regex. Show activity on this post. No, it's not valid, probably because the ASCII values are not consecutive from z to A.


2 Answers

No, a (97) is higher than Z (90). [a-Z] isn't a valid character class. However [A-z] wouldn't be equivalent either, but for a different reason. It would cover all the letters but would also include the characters between the uppercase and lowercase letters: [\]^_`.

like image 145
John Kugelman Avatar answered Oct 05 '22 23:10

John Kugelman


I'm not sure about other languages' implementations, but in PHP you can do

"/[a-z]/i"

and it will case insensitive. There is probably something similar for other languages.

like image 37
helloandre Avatar answered Oct 06 '22 01:10

helloandre