Given a list:

(setq mylist '("a1" "a2" "b1" "b2"))

How to delete all elements that match ^a?

What I want is "a1" and "a2" deleted, only left "b1" and "b2" in the list.

  • Note that "alist" is lisp terminology meaning "association list", which is a very specific kind of structure. I've edited the code to eliminate that confusion.
    – phils
    Sep 17 '18 at 15:40
  • Note also that ^ matches beginning-of-line, not beginning-of-string; see (elisp) Syntax of Regexps for how to do the latter, which is probably what you want here.
    – Basil
    Sep 17 '18 at 19:59
  • @Drew Ah, we're at editing cross-purposes here. I've been removing references to alist (because there was none -- I honestly thought it was probably a contraction of "a list" which was written without knowledge of association lists). You've been adding them, though :) AFAICS the question isn't actually about alists.
    – phils
    Sep 17 '18 at 23:42
  • @phils: Sorry; my bad. You're right, of course. The question is not about alists.
    – Drew
    Sep 18 '18 at 1:38

Do you want a new list that has only elements "b1" and "b2"? Or do you want the same list structure, but modified to have removed elements "a1" and "a2"?

@rpluim shows one way to do the former. A similar way to do the latter is to use cl-delete-if instead of cl-remove-if.

(setq mylist  (cl-delete-if (lambda (k) (string-match-p "^a" k)) mylist)

(Make sure you set variable mylist to the result returned by cl-delete-if, if you expect that variable's value to reflect the deletion properly in all cases. See the Elisp manual, node Rearrangement for more about this.)

  • My name has an i in it, but single-character edits are not allowed. sigh
    – rpluim
    Sep 18 '18 at 7:47
  • @rpluim: Sorry 'bout that; corrected.
    – Drew
    Sep 18 '18 at 13:42

There are many ways to do this, here's one:

(setq mylist (cl-remove-if (lambda (k)
                            (string-match "^a" k))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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