# File lib/bson/bson_ruby.rb, line 487
    def serialize_regex_element(buf, key, val)
      buf.put(REGEX)
      self.class.serialize_key(buf, key)

      str = val.source
      # We use serialize_key here since regex patterns aren't prefixed with
      # length (can't contain the NULL byte).
      self.class.serialize_key(buf, str)

      options = val.options
      options_str = ''

      if val.is_a?(BSON::Regex)
        options_str << 'i' if ((options & BSON::Regex::IGNORECASE) != 0)
        options_str << 'l' if ((options & BSON::Regex::LOCALE_DEPENDENT) != 0)
        options_str << 'm' if ((options & BSON::Regex::MULTILINE) != 0)
        options_str << 's' if ((options & BSON::Regex::DOTALL) != 0)
        options_str << 'u' if ((options & BSON::Regex::UNICODE) != 0)
        options_str << 'x' if ((options & BSON::Regex::EXTENDED) != 0)
      else
        options_str << 'm' # Ruby regular expressions always use multiline mode
        options_str << 'i' if ((options & Regexp::IGNORECASE) != 0)
        # dotall on the server is multiline in Ruby
        options_str << 's' if ((options & Regexp::MULTILINE) != 0)
        options_str << 'x' if ((options & Regexp::EXTENDED) != 0)
      end

      options_str << val.extra_options_str if val.respond_to?(:extra_options_str)
      # Must store option chars in alphabetical order
      self.class.serialize_cstr(buf, options_str.split(//).sort.uniq.join)
    end