| Category: | Utility Scripts |
| Author/Contact Info | /msg mrbbking |
| Description: | 2002-01-09 Update: Note to Posterity - there are better ways than this. A new guy here was confused by the difference between "capturing" with parens and "grouping" with brackets. I gave him this function to help show the difference, but it's useful for general testing of regular expressions. The thing to remember is that it's easier to write a regex that matches what you're looking for than it is to write one that also doesn't match what you're not looking for. Note: I did not use the 'quote regex' qr//; because that makes print display the regex in a way that differs from what the user typed. My goal here is clarity. Further Reading (in increasing order of difficulty):
|
#!/usr/bin/perl -w
use strict;
sub matches_regex{
## Purpose: Means to test wether a Regular Expression
## matches what you think it matches.
## Requires: One regex and one a scalar to use it on.
## Returns: True (1) for matches, false (0) for non-matches.
## ==========================================================
## Usage: "matches_regex( 'string to test', 'regex to use' );
## ==========================================================
my ($string, $regex) = @_;
return( $string =~ /$regex/ );
}
# ===== illustrations =====
my $string = '4245581234567890';
my @regexes = ('^[424558][0-9]{10,10}$'
,'^(424558)[0-9]{10,10}$'
,'^424558[0-9]{10,10}$'
);
foreach my $regex( @regexes ){
print "Testing string '$string' for regex '$regex'\n";
if( matches_regex( $string, $regex ) ){
print "\tMatched\n";
} else {
print "\tDid not match\n";
}
}
|
|
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re (tilly) 1: Regex Checker
by tilly (Archbishop) on Jan 08, 2002 at 21:47 UTC | |
by mrbbking (Hermit) on Jan 08, 2002 at 22:59 UTC | |
|
Re: Regex Checker
by Juerd (Abbot) on Jan 08, 2002 at 20:23 UTC |