TransWikia.com

Filter list by regexps

Emacs Asked by Lorem Ipsum on September 2, 2021

How can I get all elements of a list which don’t match multiple
patterns? The patterns are given as a list.

For instance, I want all files without '("no" "nix") in them.

(setq se-have
      '("~/site/src/good-org.org"
        "~/site/src/bad-no-org.org"
        "~/site/src/yes-to-org.org"
        "~/site/src/nix-this.org"
        "~/site/src/know-this-will-go.org"
        "~/site/src/is-always-next-to.org"))
(setq se-want
      '("~/site/src/good-org.org"
        "~/site/src/yes-to-org.org"
        "~/site/src/is-always-next-to.org"))

I can do it for a single pattern:

(seq-filter
 (lambda (x) (not (string-match-p (regexp-quote "no") x)))
 se-have)

How could I do this for each pattern in a list?

2 Answers

You're essentially saying you want to match any of a list of patterns.

regexp-opt takes a list of strings and produces a single regexp which matches any of them.

(regexp-opt '("no" "nix"))
=> "\(?:n\(?:ix\|o\)\)"

Note that the individual strings in the input list are not regexps -- the end result will be analogous to using regexp-quote for each string.

The equivalent rx syntax is:

(rx (or "no" "nix"))

Correct answer by phils on September 2, 2021

(seq-filter
 (lambda (x) (and (not (string-match-p (regexp-quote "no") x))
                  (not (string-match-p (regexp-quote "nix") x))))
  se-have)

Or use cl-remove-if-not. Or use seq-filter or cl-remove-if-not twice, instead of and. And so on.

Answered by Drew on September 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP