Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional regex match?

Tags:

regex

perl

How can I match an optional character in a regex expression?

I am trying to write a small file that does a little housekeeping to our NAS.

The script goes through the folders inside the specified root folder.

For my testing the root is C:\Users\Solignis\Desktop\Orders

This is where I have the first match take place, it checks to be sure the file matches our standard name convention which is the city + 3 digit folder + 3 digit file number.

Sometimes though we have extra files that have a _1 or _2 on them to denote an additional page.

How can I make this regex expression also fit the "optional" _1 or _2 and sometimes _3 into the match?

The code:

$file =~ /^ ((C[A|F|L]|ME)) (\d{3}) (\d{3}) \. (PDF) /xmi

I am sure this is easy bit I still got loops on the brain from having to "drill" into this giant hash of arrays I made which is something like 25k files in some of the arrays.

Any help would be much appreciated.

Thanks

like image 734
ianc1215 Avatar asked May 12 '11 01:05

ianc1215


2 Answers

Something like (_[1-3])?

? Matches zero or one instance.

might be what you are looking for.

like image 141
jisaacstone Avatar answered Nov 03 '22 01:11

jisaacstone


Something like (?: _[1-3] )? if don't want to catch this group.

like image 37
gangabass Avatar answered Nov 02 '22 23:11

gangabass