By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,148 Members | 748 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Character Classes and Special Characters

KevinADC
Expert 2.5K+
P: 4,059
Purpose

The purpose of this article is to discuss the difference between characters inside a character class and outside a character class and some special characters inside a character class. This is not a regular expression tutorial. Assumes you are already familiar with basic regular expression concepts and terminology. If not, you may want to read some regular expression tutorial. See the end of the article for links to online resources.

What is a Character Class?

Perl uses square brackets [...] in a regular expression to define a class of characters that can match in any order. If you have a character class of [abc] and a string 'cab' the first character to match will be the 'c' because the order in which you list the characters inside the square brackets is ignored.

Inside and Outside a Character Class and the Dot '.'

Perl treats most characters you use in regular expressions differently when used inside of a character class. The one character that seems to cause the most confusion is the dot: '.'. Outside of a character class the dot is used for wildcard matching. A dot can match anything. A dot with a quantifier can match different quantities of anything.

/.?/ (zero or one)
/.*/ (zero or more)
/.+/ (one or more)
/.{1,4}/ (minimum 1, maximum 4)

In order to match a literal dot in a pattern you have to escape it with a backslash:

$foo =~ /\./;

Note: You can also use perls \Q modifier to escape most meta characters in search patterns.

Inside a character class a dot has no meta meaning (no special meaning). It is not used for wildcard matching like it is outside a character class but is instead treated as a literal dot. There is no need to escape it when used inside a character class. It does not hurt to escape it if you prefer to write your code that way but it is not necessary.

These examples are all the same:

/[.]/
/\Q.\E/
/[\.]/


Of course it would a bit silly to have a character class of only a dot but there is a situation where it is useful: a negated character class. More on that later.

The Special Characters

Inside a character class the set of special characters are - ] \ ^ $ and are matched using an escape:

/[\-\]\\\^\$]

It seems obvious why the two characters ] \ need to be escaped so I won't discuss them further.

The scalar data type symbol $ is interpolated inside a character class which means you can create dynamic character classes:

Expand|Select|Wrap|Line Numbers
  1. my $character_class = q{#!*?};
  2. if ($foo =~ /[$character_class]/) {
  3.    ...
  4. }
  5.  
The ^ character is used to define a negated character class which I mentioned above. A negated character class means to not match what is to the right of the ^:

Expand|Select|Wrap|Line Numbers
  1. unless ($foo =~ /[^.?!]/) {
  2.    ...
  3. }
]

It is very similar to:

Expand|Select|Wrap|Line Numbers
  1. unless ($foo !~ /[.?!]/) {
  2.    ...
  3. }
It may in fact be the same but I am not sure as of this writing. Feel free to let me know. Since this is not a regular expression tutorial I am not going to discuss negated character classes in more detail.

The final special character is the dash -. Because it is interpolated as the range operator inside a character class (the same as outside a character class) it must also be escaped to match a literal - in a pattern. An example of a range of characters:

[0-9a-zA-Z]

perl fills in all the characters that logically fall in between the two ends of the range. 0-9 is the same as 0123456789 and a-z is all lowercase alpha characters and A-Z ia all uppercase alpha characters.

Two Exceptions to the Rule

I said previously that the set of characters -]\^$ must be escaped in order to match them inside of a character class. Well, those familiar to perl know only too well that there are often exceptions to the rule. The exceptions in this case are -^. The ^ only must be escaped if it is the only character in a character class:

/[\^]/

If you use it in any other position inside a character class it has no special meaning, for example:

[\d\s^\t]

the ^ is treated as a literal ^ in the above character class. The same is true for the range character -. If you use it as the only character, or as the first or last character in a character class it does not need to be escaped to match a literal - in a pattern:

/[abc-]/
/[-abc]/
/[-]/


the - is treated as a literal - in the above examples.

Review

Character classes are one example of how perl can be a bit hazy and confusing at times. Of course the same is true for most programming languages but perl seems to be a bit fast and loose at times with syntax and characters having several meanings depending on usage and context. I guess you either grow to accept this behavior or not.

Kevin (aka KevinADC)

Resources

perldoc.perl.org : Perl regular expressions quick start
perldoc.perl.org : Perl regular expressions tutorial
www.perl.org : Beginning Perl by Simon Cozens

This article is protected under the Creative Commons License.
Oct 28 '07 #1
Share this Article
Share on Google+
3 Comments


KevinADC
Expert 2.5K+
P: 4,059
Comments, corrections, discussions are welcome.
Oct 28 '07 #2

Kelicula
Expert 100+
P: 176
Comments, corrections, discussions are welcome.
Very interesting.
I was working on something yesterday, (converting carriage returns into line breaks with user inputted data) and noticed that this:
Expand|Select|Wrap|Line Numbers
  1.  
  2. my $content = $q->escapeHTML( $q->param('content'));
  3.  
  4. $content =~ s/[\r\n]/<br \/>/g;
  5.  
  6.  
Is NOT the same as this:
Expand|Select|Wrap|Line Numbers
  1.  
  2. my $content = $q->escapeHTML( $q->param('content'));
  3.  
  4. $content =~ s/(\r\n)/<br \/>/g;
  5.  
  6.  
It seamed that when included in a character class, it translated to "change \r AND \n into <br />", but when included as a group it meant "change \r OR \n into <br />".

I have heard that usually these "( )" do the right thing. And to stay away from these "[ ]" unless you really know what you're doing..

Elaborate??
Feb 3 '08 #3

KevinADC
Expert 2.5K+
P: 4,059
It seamed that when included in a character class, it translated to "change \r AND \n into <br />", but when included as a group it meant "change \r OR \n into <br />".

I have heard that usually these "( )" do the right thing. And to stay away from these "[ ]" unless you really know what you're doing..

Elaborate??
The character class means to change any of the characters that match, regardless of order.

In the grouped characters it means to change them only if both \r and \n are matched and in that order.

A character class is is basically a group of things that can match in any order. Roughly the same as a grouped list that uses aternation:

Expand|Select|Wrap|Line Numbers
  1. [abcd1234]
  2.  
  3. (a|b|c|d|1|2|3|4|)
  4.  
if you do not use alternation in a grouped list they have to match in exact order.

Your example uses the "g" modifer which is also affecting the way the regexps work. Remove it and you will see a difference.
Feb 4 '08 #4