Learning Regular Expressions for Beginners: Building a Regular Expression Tester

Last updated: Nov 7, 2008

When learning regular expressions it is helpful to be able to quickly test regular expression patterns. It doesn’t really matter which proramming language you use to build it but I will give you two examples, one in Perl and one in PHP.

If you are new to regular expressions first check out, Learning Regular Expressions For Beginners: The Basics. It will run your through your first example. Once you have the hang of it you can come back here and build a test program to practice your own regular expressions.

Regular Expression testing for Perl

Just open up a text editor and copy and paste the code below. To use it just replace the part that says, “YOUR_REGULAR_EXPRESSION_GOES_HERE”. Each new line that you type into the console will be tested. Use ctrl+c to quit.

#!/usr/bin/perl
while (<>) {                        
  chomp;
  if (/YOUR_REGULAR_EXPRESSION_GOES_HERE/) {
    print "Matched: |$`<$&>$'|\n";  
  } else {
    print "No match: |$_|\n";
  }
}

|beforeafter|

Regular Expression testing for PHP

$testString = $_POST['testString'];
preg_match('/YOUR_REGULAR_EXPRESSION_GOES_HERE/', $testString, $matches);
print_r($matches);
?>

<html>
<head><title>Regular Expresion Tester</title></head>
<body>
<form action="" method="POST">
    <input type="textbox" name="testString" /><br />
    <input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Get notified on new posts or other things I'm working on

Share: