I'd like to write something like this except to compare the region with a regexp.

(if (string-match (buffer-substring-no-properties (point) (mark))

Is there an equivalent of string-match for regexp that I can use like this

(if (regexp-match (buffer-substring-no-properties (point) (mark))

so that it returns true if the selected region is "Apple" and nil if it's "apple"?

  • 9
    A few random remarks : (i) string-match already uses regexps (ii) let-bind case-fold-search to nil around your call if you want case sensitivity (iii) use looking-at for matching text at point (iv) you can use region-beginning and region-end instead of point and mark in case the latter is before the former (bonus point for making sure use-region-p is non-nil)
    – YoungFrog
    Commented Jan 18, 2016 at 11:40
  • 2
    @YoungFrom I think item (i) qualifies as an answer.
    – T. Verron
    Commented Jan 18, 2016 at 12:40
  • 4
    C-h f string-match would tell you. Commented Jan 18, 2016 at 16:51

1 Answer 1


For the sake of an answer:

string-match is meant for to be used with regexps.

(string-match REGEXP STRING &optional START)

Return index of start of first match for REGEXP in STRING, or nil. Matching ignores case if ‘case-fold-search’ is non-nil. If third arg START is non-nil, start search at that index in STRING. For index of first char beyond the match, do (match-end 0). ‘match-end’ and ‘match-beginning’ also give indices of substrings matched by parenthesis constructs in the pattern.

You can use the function ‘match-string’ to extract the substrings matched by the parenthesis constructions in REGEXP.

Here are some examples

(string-match "\\(dog\\|cat\\)" "There is a dog.") ;; => 11
(string-match "\\(dog\\|cat\\)" "There are two cats here." 0) ;; => 14
(string-match "\\(dog\\|cat\\)" "There are two cats here." 15) ;; => nil
(string-match "\\(dog\\|cat\\)" "There are horses.") ;; => nil

Note that if you don't plan on using match-data after using string-match you should prefer to use string-match-p which works just like string-match except that it doesn't modify match-data when run.

As other have said, in your case looking-at would probably be a better choice anyway.

(looking-at REGEXP)

Return t if text after point matches regular expression REGEXP. This function modifies the match data that ‘match-beginning’, ‘match-end’ and ‘match-data’ access; save and restore the match data if you want to preserve them.

  • Given that the OP got the argument order wrong, it would probably be a good idea to show an example snippet calling string-match.
    – Malabarba
    Commented Feb 9, 2016 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.