Search code examples
regexperlpcre

Regular Expression that matches a word, or nothing


I'm really struggling to put a label on this, which is probably why I was unable to find what I need through a search.

I'm looking to match the following:

  • Auto Reply
  • Automatic Reply
  • AutomaticReply

The platform that I'm using doesn't allow for the specification of case-insensitive searches. I tried the following regular expression:

.*[aA]uto(?:matic)[ ]*[rR]eply.*

Thinking that (?:matic) would cause my expression to match Auto or Automatic. However, it is only matching Automatic.

  • What am I doing wrong?
  • What is the proper terminology here?

This is using Perl for the regular expression engine (I think that's PCRE but I'm not sure).


Solution

  • (?:...) is to regex patterns as (...) is to arithmetic: It simply overrides precedence.

     ab|cd        # Matches ab or cd
     a(?:b|c)d    # Matches abd or acd
    

    A ? quantifier is what makes matching optional.

     a?           # Matches a or an empty string
     abc?d        # Matches abcd or abd
     a(?:bc)?d    # Matches abcd or ad
    

    You want

    (?:matic)?
    

    Without the needless leading and trailing .*, we get the following:

    /[aA]uto(?:matic)?[ ]*[rR]eply/
    

    As @adamdc78 points out, that matches AutoReply. This can be avoided as using the following:

    /[aA]uto(?:matic[ ]*|[ ]+)[rR]eply/
    

    or

    /[aA]uto(?:matic|[ ])[ ]*[rR]eply/