PDA

View Full Version : Pattern Matching and Regular Expressions


Yakisoba
03-01-2005, 09:12 AM
Ive completed many online tutorials regarding regexp, but I cant seem to construct anything to deal with the following situation.

The format of Login IDs is ######### (or ##a######) but, depending on the type of user a login may be entered 4 different ways.

Login ID type 1 = ##a###### (in this case nothing needs to be done)

Login ID type 2 = a##a###### (in this case the first character needs to be ignored)

Login ID type 3 = ##a######a (in this case the last character needs to be ignored)

Login ID type 4 = a##a######a (in this case the first and the last character need to be ignored)

(in general login IDs will never begin or end with a letter and are 9 characters long)

without using "if" statements is it possible to create a single regular expression that will match the 9 character login ID?

Any help regarding this matter would be greatly appreciated.

Thanks.

Catman
03-01-2005, 05:22 PM
If I'm understanding your question correctly:

$loginValue =~ s|^\D||;
$loginValue =~ s|\D$||;

This will strip the first character, only if it's not a number, and the last character, only if it's not a number. In short, this reduces all cases to type 1, so you need only test for $loginValue in that case.

If it's important to have the original $loginValue data, you can copy it to another variable.

Here's a short test script for illustration:

#!/usr/local/bin/perl
use strict;
use CGI ':standard';
use CGI::Carp "fatalsToBrowser";

my ($testString1, $testString2, $testString3);

$testString1 = "a12x123b";
$testString1 =~ s|^\D||;
$testString1 =~ s|\D$||;

$testString2 = "a12x1233";
$testString2 =~ s|^\D||;
$testString2 =~ s|\D$||;

$testString3 = "112x123b";
$testString3 =~ s|^\D||;
$testString3 =~ s|\D$||;

print "Content-type: text/html\n\n";

print "$testString1\n";
print "$testString2\n";
print "$testString3\n";
The output will be:

12x123
12x1233
112x123

Yakisoba
03-03-2005, 07:59 AM
Thanks Catman,

Your input made things a lot easier...I was trying to pull off something that looked like this:

$logname =~ /\D(?:[[:alpha:]]([[:alnum:]]{11})[[:alpha:]])\D/;


your way is MUCH better...Im still not sure if what I was trying to do is possible.