help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: help with regexp function


From: B. T. Raven
Subject: Re: help with regexp function
Date: Fri, 24 Nov 2017 08:46:59 -0600
User-agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.4.0

On 11/23/2017 09:20, Stephen Berman wrote:

Here's a pretty direct translation of the interactive substitution:
This works correctly but it isn't exactly what regexp-quote returns.

Note that (regexp-quote "\(^[0-9]+ \)\(.+\)") returns this string:
"(\\^\\[0-9]\\+ )(\\.\\+)", which matches only the literal string
"(^[0-9]+ )(.+)", so it's not what you want.

Is there a function that produces "^\\([0-9]+\\) \\(.*\\)$" from
"\(^[0-9]+ \)\(.+\)" ?

I don't know of any.  But in order for the Lisp reader to recognize a
backslash in a string as a backslash, you have to double it (because the
backslash is used as the escape character is the Lisp read syntax).  So
you can just write your regexp as you would when using
query-replace-regexp and then double each of the backslashes to use it
in a Lisp program.

Okay, thanks.


Did you replace .+ with .* just for greater generality?

Yep.



No, I don't understand that notation. I started with other regexp
functions like query-replace-regexp but was getting type errors and
general confusion.

I still can't tell how such errors arose, but it's probably not worth
pursuing now.

;; I have a function which is a black box to to me but it works in
the larger context I have it in. Does match-string do something like
this implicitly (casting a list as a string?)

Not AFAIK.

Here is the function I was talking about:
(defun reverse-string (str)
   (apply #'string (nreverse (string-to-list str))))

It sounded like (append #'string ... was recasting a list to a string.
                    ^^^^^^
                    apply
Yes, because I tried to type rather than copypaste.
I was distracted by the # (what does it mean?)



I'm not sure it's helpful to think of it like that, since using a list
is an artefact of the function definition here: `string' takes one or
more characters but Emacs Lisp functions cannot return multiple values,
only single values such as a list of characters.  But you can dispense
with that intermediate step:

(defun reverse-string (str)
   (let ((l (length str))
        (nstr ""))
     (dotimes (i l nstr)
       (setq nstr (concat (string (aref str i)) nstr)))))

In fact, this is essentially how `nreverse' (and 'reverse') operate on
strings (so there's no need for `reverse-string').  In any case, I don't
see what this has to do with match-string.

That looks like it may be faster than what
I have now. Is it? Everything is in C except dotimes and string-to-list according to the function docs.


Thanks again.


Steve Berman





reply via email to

[Prev in Thread] Current Thread [Next in Thread]