473,287 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,287 developers and data experts.

Character Classes and Special Characters

KevinADC
4,059 Expert 2GB
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
3 10146
KevinADC
4,059 Expert 2GB
Comments, corrections, discussions are welcome.
Oct 28 '07 #2
Kelicula
176 Expert 100+
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
4,059 Expert 2GB
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

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: quickcur | last post by:
I am rewrite some of my excel sheets to xml document. In my excel, there is a lot of special characters like "/", " " (space), "#", "+'. I am using a java program based on JDom to to create xml....
3
by: Ekempd | last post by:
I'm trying to read the following XML file: <mail> <from>Rae</from> <subject>Informacion de su Proceso de Titulacion</subject> <body_mail> <!]> </body_mail> </mail>
7
by: teachtiro | last post by:
Hi, 'C' says \ is the escape character to be used when characters are to be interpreted in an uncommon sense, e.g. \t usage in printf(), but for printing % through printf(), i have read that %%...
18
by: james | last post by:
Hi, I am loading a CSV file ( Comma Seperated Value) into a Richtext box. I have a routine that splits the data up when it hits the "," and then copies the results into a listbox. The data also...
1
by: sonald | last post by:
Dear All, I am working on a module that validates the provided CSV data in a text format, which must be in a predefined format. We check for the : 1. Number of fields provided in the text file,...
14
by: Shhnwz.a | last post by:
Hi, I am in confusion regarding jargons. When it is technically correct to say.. String or Character Array.in c. just give me your perspectives in this issue. Thanx in Advance.
17
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, Wide character and multi-byte character are two popular encoding schemes on Windows. And wide character is using unicode encoding scheme. But each time I feel confused when...
3
by: jeyabarani | last post by:
Hi guys, I want to check whether the user has entered any special characters in a text box. If the user enters, i want to display an alert message stating that he cant enter a special character...
2
by: Sallu | last post by:
Hi all and one i wrote this script, working fine without fail( just run it) import re value='This is Praveen' print value #value = 'riché gerry' #words=str(value.split()).strip('').replace(',...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.