protected function buildRegExp($pattern)
    {
        $pattern = '/' . trim($pattern, '/');
        $pattern = str_replace('/', '\/', $pattern);
        preg_match_all('#((\\\/)?[^\\\/]+)#im', $pattern, $patternMatches);

        foreach ($patternMatches[1] as &$match) {
            if (strpos($match, '*') !== false) {
                $match = str_replace('*', self::ANY, $match);
            }

            if (preg_match('#\(![^\)]+\)#i', $match)) {
                $match = preg_replace_callback(
                    '/^(.*)\(!([^\)]+)\)$/i',
                    array($this, 'buildRegExpCallback'),
                    $match,
                    \PREG_SET_ORDER
                );
            }

            unset($match);
        }

        $pattern = str_replace($patternMatches[0], $patternMatches[1], $pattern);
        $pattern = '/^' . $pattern . '\/?.*$/i';

        return $pattern;
    }