[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Improve `replace-regexp-in-string' ergonomics?
From: |
Thierry Volpiatto |
Subject: |
Re: Improve `replace-regexp-in-string' ergonomics? |
Date: |
Wed, 22 Sep 2021 07:47:14 +0000 |
Yuri Khan <yuri.v.khan@gmail.com> writes:
> However, I have a hypothesis that what users really want is “I have
> this list of pattern/replacement pairs, and I want to go through each
> occurrence of each pattern in the original text, and replace them with
> their respective replacements”, without thinking about intermediate
> buffer contents. In simple cases, this can be simulated by
> parenthesizing each pattern, joining them all with a \|, and using the
> resulting super-pattern to iterate through occurrences, then,
> depending on which group matched, doing the replacement. (Harder cases
> include those where patterns have capturing groups and/or
> backreferences.)
Instead of using a list like
(pattern replacement pattern replacement etc...)
perhaps a list like (pattern subexp replacement ...) then you can loop
in this list doing the replacement with those 3 elements, something like
this:
(defun tv/replace-regexp-in-string (regexps string &optional fixedcase
literal)
(cl-assert (zerop (% (length regexps) 3)))
(cl-loop with str = string
for (m s r) on regexps by 'cdddr
do (setq str (replace-regexp-in-string
m r str
fixedcase literal s))
finally return str))
With previous example it give:
(let ((results "['foo', 'bar', 'baz']"))
(tv/replace-regexp-in-string
'("\\[" 0 "("
"\\]" 0 ")"
",[[:space:]]" 0 " "
"'" 0 "\"")
results))
"(\"foo\" \"bar\" \"baz\")"
--
Thierry
Re: Improve `replace-regexp-in-string' ergonomics?, Adam Porter, 2021/09/22
Re: Improve `replace-regexp-in-string' ergonomics?, Andreas Schwab, 2021/09/22
Re: Improve `replace-regexp-in-string' ergonomics?, Augusto Stoffel, 2021/09/22