6

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.

4
  • 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
    Commented Sep 17, 2018 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
    Commented Sep 17, 2018 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
    Commented Sep 17, 2018 at 23:42
  • @phils: Sorry; my bad. You're right, of course. The question is not about alists.
    – Drew
    Commented Sep 18, 2018 at 1:38

2 Answers 2

6

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.)

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

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

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

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.