Home / code / cgi

Regular expression

Simple use of regular expression

If you want to find a string in a string, you use the regular expression (or regex).

$name =~ /von/
The above example gives TRUE, if the string von is in the string $name. If Von is in the string, it is registered as FALSE. Regex is case sensitive. If you add the i option you make it case insensitive.
$name =~ /von/i
You can add meta-characters to make searching easy. You can use [] to search for a set of several characters. The next example search for Carl and Karl.
$name =~ /[CK]arl/
You can also exclude characters. Let's say that you are not interested in Carla or Karla.
$name =~ /[CK]arl[^a]/
The meta-character ^ has also another meaning. Say you are searching for a word that starts with j.
$name =~ /^j/i

Example:

print "What do you read before asking a question?";

chomp ($answer=<STDIN>);

if ($answer =~ /faq/i)
{
  print "Right! You're a perfect student! \n";
}
else
{
  print "Begone, vile creature! \n";
}
You also have the special variable $_. If you use this variable you don't have to use the =~.
print "What do you read before asking a question?";

chomp ($_=<STDIN>);

if (/faq/i)
{
  print "Right! You're a perfect student! \n";
}
else
{
  print "Begone, vile creature! \n";
}

Substitution

You can do more then just search, you can also replace. This is called substitution. You do this with s///. Between the slashes you place the to search and the replace strings. For example if you want to replace Eli with Tom:

$_="Eli is a really good teacher!";

print "$_\n";

s/Eli/Tom/;

print "$_\n";
You can also make substitution case insensitive with the i option.
$_="Eli is a really good teacher!";

print "$_\n";

s/eli/Tom/i;

print "$_\n";
Normally a substitution will only happens once. If you want it to happen more as once, you have to add the g option.
$_="Eli is a really good teacher! Eli is the best!";

print "$_\n";

s/eli/Tom/ig;

print "$_\n";

Split and Join

The split function exists of 2 parts. The first part tells where it should be split. The second part tells which string should be split.

$line="Tom;Bert;Frank;Eli;Brigitte";

print "$line \n";

@fields = split (/;/, $line);

foreach $field(@fields)
{
  print "$field \n";
}
If you use the special variable $_ for the to split string, you can make it a lot shorter.
$line="Tom;Bert;Frank;Eli;Brigitte";

print "$_ \n";

@fields = split (/;/);

foreach (@fields)
{
  print "$_ \n";
}

You also have the join function. With join you put the pieces back together. The join function exists of 2 parts. The first part is the "glue" operator, the operator needed to separate the parts. The second part has the different strings that need to glued.

$name1="Tom";
$name2="Bert";
$name3="Frank";
$name4="Eli";
$name5="Brigitte";

$fields = join(";", $name1, $name2, $name3, $name4, $name5);

print "$fields";

 

TOP

Latest script:

 

Books: