Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression that matches a word, or nothing

Tags:

regex

perl

pcre

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).

like image 903
crush Avatar asked Jan 17 '14 18:01

crush


People also ask

What would be the regular expression to match a blank line?

The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string.

What is the regex for anything?

(wildcard character) match anything, including line breaks. Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.


2 Answers

(?:...) 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/
like image 157
ikegami Avatar answered Sep 24 '22 04:09

ikegami


This should work:

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

you were simply missing the ? after (?:matic)

like image 33
Hunter McMillen Avatar answered Sep 22 '22 04:09

Hunter McMillen