Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression with Perl ?

Status
Not open for further replies.

markshen2004

Programmer
Jun 9, 2004
89
CA
Hi there

I need write a regular expression with Perl .I have to search according to the conditions.

- 8 characters maximum
- Position 1 (if it exist) -- numeric only
- Position 2 (if it exist) -- alpha-numeric -- "1 - 0; A - R;"
- Position 3 (if it exist) -- alpha-numeric -- "1 - 0; A - Z;"
- Position 4 - 8 (if they exist) -- numeric only

I write it as /[0-9][1-0A-R][1-0A-Z][0-9]{1,5}/. but I do not know why it doesn't work.
Please give me some idea to modify it.

Thanks a lot


 
The regular expression you indicated will only work if ALL the conditions you said are working... maybe that's why you have a problem.

I don't understand too much the meaning of "if exist" for all of them? what do you actually want... try to give examples... it help to understand.
 
Try writing 1-0 as 01 within character classes. I don't think 1-0 is valid as a range.

For "if it exists", use ? (zero or one occurences).

Anchoring your expression with ^ and $ would also be a good idea.

You should probably look at the following links if you haven't already (or even if you have):


I hope this helps. If you're still having trouble, some examples as naq2 suggests would be good.
 
Mark,
I am assuming since you mention positions, there will be a space if a position does not exist. I added the '\s' which checks for a space.

You can fill in the following code for your own test cases.

Code:
#!/usr/bin/perl
#the following match:
&check("10F58365");
&check(" 1Z5 32 ");
&check("9R1     ");
&check("       1");
&check("90134567");
&check("000     ");

#the following do not match:
&check("000");
&check("A0000000");
&check("1ZZ12345");
&check("12345678");

sub check {
        if ($_[0]=~/^[\d\s][\s01A-R][\s01A-Z][\d\s][\d\s][\d\s][\d\s][\d\s]$/){
                print "Matched: $_[0]\n";
        }
        else {
                print "Did not match: $_[0]\n";
        }
}

If the string will not contain spaces, or might contain spaces, you can use this line instead:
Code:
if ($_[0]=~/^[\d\s]?[\s01A-R]?[\s01A-Z]?[\d\s]?[\d\s]?[\d\s]?[\d\s]?[\d\s]?$/){
The added question marks will check for zero or one instance, like mike says above. The downside to this method is that this string can be matched: "1Z".

Hopefully this helps you, or at least points you in the right direction...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top