2005-04-25

Simple Perl and C# Regex Comparison

I have been working through Regular Expressions from Friedl. I have been testing the regexes in PowerGrep, EditPad Pro, Perl, and C# in .NET. Here is a very simply comparison:

Here is the Perl script borrowed from Friedl:

print "Enter a temperature (e.g., 32F or 100C):\n";
$input = ;
chomp($input);

if ($input =~ m/^([-+]?[0-9]+(\.[0-9]*)?)([cC][fF])$/)
{
$InputNum = $1;
$type = $3;

if($type eq "C")
{
$celsius = $InputNum;
$fahrenheit = ($celsius * 9 / 5) + 32;
}
else
{
$fahrenheit = $InputNum;
$celsius = ($fahrenheit - 32) * 5 / 9;
}

printf "%.2f C is %.2f F\n", $celsius, $fahrenheit;

}
else
{
print "Expecting a number , then a \"C\" or a \"F\", so don't understand \"$input\".\n";
}

Here is a similar program written in C#:

using System;
using System.Text.RegularExpressions;
namespace Temperature1
{
///


/// Summary description for Class1.
///

class Class1
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a temperature to convert. (Examples: 0C or 32F)");
string input = Console.ReadLine(); // read input from user
string pattern = @"^([-+]?[0-9]+(?:\.[0-9]*)?)([CF])$"; // build regex pattern
Regex r = new Regex(pattern, RegexOptions.IgnoreCase); // Compile the regular expression.
Match m = r.Match(input); // Match the regular expression pattern against a text string.
if(m.Success)
{
string type = m.Groups[2].ToString();
double celsius = 0.0D;
double fahrenheit = 0.0D;

if(type.ToUpper()=="C") // convert from celsius to fahrenheit
{
celsius = double.Parse(m.Groups[1].ToString());
fahrenheit = (celsius * 9 / 5) + 32;
}
else // convert from fahrenheit to celsius
{
fahrenheit = double.Parse(m.Groups[1].ToString());
celsius = (fahrenheit - 32) * 5 / 9;
}

// at this point we have both temperatures, so display the results
Console.WriteLine("Result: {0,2:n} C is {1,2:n} F", celsius, fahrenheit);
}
else
{
// the initial regex did not match, so issue a warning
Console.WriteLine("Expecting a number followed by 'C' or 'F' so I don't understand {0}.", input);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
}

Regex in Perl definitely seems more natural and "built in".

Here is a link to Regex documantation on MSDN: .NET Framework Regular Expressions

More to come...

No comments: