I have the following function that uses a regexp for counting matches, but I have difficulty coming up with regexp expressions to test it.

    (defun rk-regex-count (regex rgn-beg rgn-end)
      "Count brace marks within a region with `completing-read'.
    REGEX     Regular expression.
    RGN-BEG   Marker defining start of region.
    RGN-END   Marker defining end of region."
       (list (read-regexp "Regex: ")
        (let (($sum  0))
          (goto-char rgn-beg)
          (while (and (< (point) rgn-end)
                      (re-search-forward regex rgn-end t))
            (+ $sum 1))
          (message "Marks: %s Count: %d" regex $sum)
          (goto-char rgn-beg))))

For instance, suppose I have the following piece of code and want to count the number of opening parentheses. What should my regex be? Other examples or using this function would be very illuminating.

       (list (read-regexp "Regex: ")
  • For any regular expression, the value of $sum is 0. The code (+ $sum 1) never changes the value of $sum. Why don't you use the count-matches function?
    – gigiair
    Apr 15, 2022 at 17:29

1 Answer 1

  1. You have an error in your code. Presumably you meant this: (setq $sum (+ $sum 1)) and not this: (+ $sum 1).

  2. For regexps to try, it depends on what you're wanting to match, of course. Try a regexp such as this (after the fix of #1:), for instance: ([^)]*).

  • Your regexp matches "any number of any char but )". It gives me a count of 3, but I am getting quite confused about the result.
    – Dilna
    Apr 15, 2022 at 19:26
  • The regexp matches ( followed by zero or more chars other than ), followed by ). It's just an example - nothing special. Dunno what you really might want to match, and that's anyway left up to the user of your command.
    – Drew
    Apr 15, 2022 at 19:29
  • You are correct. I am simply trying to test the function a little bit.
    – Dilna
    Apr 18, 2022 at 0:09
  • I am getting Invalid regexp: "Unmatched [ or [^"
    – Dilna
    Apr 18, 2022 at 0:17
  • Perhaps you didn't type the whole regexp, and do so correctly. Or perhaps you didn't apply the code correction (#1) properly.
    – Drew
    Apr 18, 2022 at 14:11

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.