diff --git a/ctools_automodal.module b/ctools_automodal.module
index e706bc2..4ce46f1 100644
--- a/ctools_automodal.module
+++ b/ctools_automodal.module
@@ -18,6 +18,8 @@ function ctools_automodal_module_implements_alter(&$implementations, $hook) {
 function ctools_automodal_menu_alter(&$items) {
   $modal_paths = array();
 
+  $all_paths = array_keys($items);
+  $convert_to_regexp = function ($value) { return preg_replace('/%[^\/]*/', '[^/]+', $value); };
   foreach ($items as $path => $item) {
     if (!empty($item['modal']) && strpos($path, '%ctools_js') === FALSE) {
       if ($item['page callback'] == 'drupal_get_form') {
@@ -33,29 +35,22 @@ function ctools_automodal_menu_alter(&$items) {
         $items["$path/%ctools_js"]['page arguments'][] = substr_count($path, '/') + 1;
         $items["$path/%ctools_js"]['type'] = MENU_CALLBACK;
       }
-      $modal_paths[] = preg_replace('/%[^\/]*/', '*', $path);
+      $modal_regexp_pieces[] = $convert_to_regexp($path);
+      $modal_paths[] = $path;
     }
   }
+  $modal_regexp = '@^' . implode('|^', $modal_regexp_pieces) . '@';
+  $not_modal_regexp = '@^' . implode('|^', array_map($convert_to_regexp, array_diff(preg_grep($modal_regexp, $all_paths), $modal_paths))) . '@';
 
-  variable_set('ctools_automodal_paths', $modal_paths);
+  variable_set('ctools_automodal_regexp', $modal_regexp);
+  variable_set('ctools_automodal_not_regexp', $not_modal_regexp);
 }
 
 /**
  * Check if an internal Drupal path should be converted to a modal link.
  */
 function ctools_automodal_is_path_modal($path) {
-  static $modal_paths_regex;
-
-  if (!isset($modal_paths_regex)) {
-    $modal_paths = variable_get('ctools_automodal_paths', array());
-    foreach ($modal_paths as &$modal_path) {
-      $modal_path = preg_quote($modal_path, '/');
-      $modal_path = str_replace('\*', '.*', $modal_path);
-    }
-    $modal_paths_regex = '/^(' . implode('|', $modal_paths) . ')$/';
-  }
-
-  return (bool) preg_match($modal_paths_regex, $path);
+  return preg_match(variable_get('ctools_automodal_regexp'), $path) && !preg_match(variable_get('ctools_automodal_not_regexp'), $path);
 }
 
 /**
