What's the exclamation mark at the beginning and dollar sign at the end of regex?

lvarayut picture lvarayut · Aug 7, 2015 · Viewed 14.5k times · Source

I"m using Mean.io and saw an regex in a modRewrite function:

app.use(modRewrite([

   '!^/api/.*|\\_getModules|\\.html|\\.js|\\.css|\\.mp4|\\.swf|\\.jp(e?)g|\\.png|\\.gif|\\.svg|\\.ico|\\.eot|\\.ttf|\\.woff|\\.pdf$ / [L]'

]));

I understand that they're trying to rewrite the url to be prettier by replacing any urls containing:

/api/, _getModules, .html, .js, ..., .pdf

However, I have been searching in order to understand the regex but still can't figure it out what is the !^ at the beginning of the line and $ at the end of the line. Could someone please extract the regex step by step?

Answer

Wiktor Stribiżew picture Wiktor Stribiżew · Aug 7, 2015

According to Apache mod_rewrite Introduction:

In mod_rewrite the ! character can be used before a regular expression to negate it. This is, a string will be considered to have matched only if it does not match the rest of the expression.

The ^ and $ are regex anchors that assert the position at the start and end of string respectively.

To understand the rest, you can go through the What does the regex mean post.

The regex itself is:

  • ^ - Assert the start of string position and...
  • /api/.* - Match literally /api/ and 0 or more characters other then newline
  • | - Or...
  • \\_getModules - Match _getModules
  • | - Or
  • \\.html - Match .html
  • |\\.js|\\.css|\\.mp4|\\.swf|\\.jp(e?)g|\\.png|\\.gif|\\.svg|\\.ico|\\.eot|\\.ttf|\\.woff| - Or these extensions (note it will match jpg and jpeg as ? means match 0 or 1 occurrence of preceding pattern)
  • \\.pdf$ - Match .pdf right at the end of the string ($).