Regex resource

http://www.virtuosimedia.com/tutorials/37-tested-php-perl-and-javascript-regular-expressions

Posted on 1 Nov 2009, 18:26 - Category: Regex
Comments - Edit - Delete


Perl Regular Expressions Continued: quantifiers, OR, ?, +, *, {}, $1

use CGI ':standard';
print header, start_html(-title=>'regex2');

? : preceding element optional

+ : 1 or greater number of preceding element allowed

* : preceding optional any quantity, be careful to limit # quantifiers as they can eat up whole expressions
# example limiting methods:
# /\(\d*\) last parenthesis limits
# also adding a ? limits (*?, +?, ??)

{m,n} : preceding min, max, if no max, max = min
{m,} : minimum, infinite
{m} : no more, no less

# pipe delimiter makes an OR match
/ice (tea/coffee)/

# matches are saved in numbered array determined # left to right by parenthesis in expression
# and are referenced afterword via $1, $2 and so on

examples:

$phone = "(547) 741-9876, 666-0987";
&check($phone);

sub check
{
if ( $_[0] =~ m/^((\(\d{3}\))? *\d{3}-\d{4},? *)+$/ )
{print "match<br />";}
}

$focus = "ice tea";
matcher($focus);

$focus = "nice coffee";
matcher($focus);

sub matcher
{

if( (@found) = $_[0] =~ /([nr]?ice (tea/coffee))/g )
{
print "OR match<br />";
print "$found[0]<br />"; # or, print $1;
print "$found[1]<br />"; # or, print $2;
}

}

Posted on 6 Oct 2009, 23:35 - Category: Regex
Comments - Edit - Delete


Perl Match Substitute Split Regular Expressions

# =~ : binding operator
# m : match
# s : substitute
# delimiter maybe be any symbol, commonly : /
# m optional if / used
# i : no case sensitivity

# example:
print "Content-type: text/html\n\n";
my $example = "hello";
if( $example =~ m/Hello/ ) { print "match"; } #false
if( $example =~ m/Hello/i ) { print "match"; } #true
$ example = s/H/j/i; print $example;
#result jello;

# special variables
# $`, $&, $'
# hold value prior to match, match, and value after match, continuing above example:
print "'$`' was prior to match<br />";
# result '' was prior to match
print "'$&' was our match<br />";
# result 'h' was our match
print "'$'' was after our match";
# result 'ello' was after out match

# Split example
my $excel = 'cat,grey,large:dog,white,small:person,green,fat:mouse,black,tiny';
my @broken_out = split(/:/, $excel);
foreach (@broken_out) {
my ($animal, $color, $size);
($animal, $color, $size) = split(/,/); # default variable $_ is being split here
print "animal: $animal : color: $color : size : $size<br />";
}

# output
# animal: cat : color: grey : size : large
# animal: dog : color: white : size : small
# animal: person : color: green : size : fat
# animal: mouse : color: black : size : tiny

Posted on 3 Oct 2009, 17:24 - Category: Regex
Comments - Edit - Delete


Pages: [1]
Loading