Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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)?$
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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