I'm working on a regex formula that will check if the supplied file for processing has either of the following formats:

  1. SN1234_filename.pdf
  2. SN1234_filename.pdf.zip

This is what I have right now:

MYFILE="SN39586_invoice.pdf"  
ISZIP=0  
if [ $ISZIP -eq 0 ]; then  
    FORMAT='^SN[0-9]+\_[a-zA-Z0-9]+\\.pdf$'  
    else  
        FORMAT='^SN[0-9]+\_[a-zA-Z0-9]+\\.pdf\\.zip$'  
    fi

if [[ $MYFILE =~ $FORMAT ]]; then  
  # Do some processing  
  else  
  echo "invalid file format"  
fi

This is working currently, but I want to get rid of the if-else block that sets the FORMAT variable. How can I optimize the FORMAT variable?

link|improve this question

71% accept rate
feedback

1 Answer

up vote 0 down vote accepted

Use the ? operator, which matches zero or one occurence of the previous character or group:

^SN[0-9]+_[a-zA-Z0-9]+\.pdf(\.zip)?$
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.