- (let ((count 0) start)
- (while (string-match "\\(\\`\\|[^\\]\\)\\\\\\(\\\\\\\\\\)*([^?]"
- regexp start)
- (setq count (1+ count)
- ;; Go back 2 chars (one for [^?] and one for [^\\]).
- start (- (match-end 0) 2)))
+ (let ((count 0) start last)
+ (while (string-match "\\\\(\\(\\?:\\)?" regexp start)
+ (setq start (match-end 0)) ; Start of next search.
+ (when (and (not (match-beginning 1))
+ (subregexp-context-p regexp (match-beginning 0) last))
+ ;; It's not a shy group and it's not inside brackets or after
+ ;; a backslash: it's really a group-open marker.
+ (setq last start) ; Speed up next regexp-opt-re-context-p.
+ (setq count (1+ count))))