how to use a variable inside Emacs regex features ?

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

how to use a variable inside Emacs regex features ?

Budi
how to use a variable inside Emacs' regex features such as
re-search-forward, looking-at, and all the rest ?

Reply | Threaded
Open this post in threaded view
|

RE: how to use a variable inside Emacs regex features ?

Drew Adams
> how to use a variable inside Emacs' regex features such as
> re-search-forward, looking-at, and all the rest ?

Use it inside how? where?

Maybe tell us what you really want to do.

Give an example, perhaps, to show what you're asking about.  In any case, `C-h f re-search-forward' should tell you what you need to know about its arguments.

Reply | Threaded
Open this post in threaded view
|

Re: how to use a variable inside Emacs regex features ?

Budi
(setq ntimes 7)
re-search-forward "hello\\{ntimes\\}"

How is above supposed to work ?

On 5/23/19, Drew Adams <[hidden email]> wrote:

>> how to use a variable inside Emacs' regex features such as
>> re-search-forward, looking-at, and all the rest ?
>
> Use it inside how? where?
>
> Maybe tell us what you really want to do.
>
> Give an example, perhaps, to show what you're asking about.  In any case,
> `C-h f re-search-forward' should tell you what you need to know about its
> arguments.
>

Reply | Threaded
Open this post in threaded view
|

Re: how to use a variable inside Emacs regex features ?

Tomas Zerolo
On Thu, May 23, 2019 at 11:46:29AM +0700, Budi wrote:
> (setq ntimes 7)
> re-search-forward "hello\\{ntimes\\}"
>
> How is above supposed to work ?

It's not supposed to work ;-)

(the specific construct above takes a constant between \{ and \}).

Usually you construct your string using whatever other facilities
Elisp has, e.g.

(let* ((ntimes 17)
       (re (format "fo\\{%d\\}" ntimes)))
  (re-search-forward re)) ; searches for 'f' followed by 17 'o's

Be extra careful for variables containing regular expression
special characters (in the above case of an int, there is no
danger). Use the function 'regexp-quote' as needed.

If you are doing more complex things, you might like 'rx', which
allows you to write regular expressions in S-expression syntax,
thus giving you access to template macros and all that goodness.

Cheers
-- t

signature.asc (205 bytes) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: how to use a variable inside Emacs regex features ?

Michael Heerdegen
<[hidden email]> writes:

> If you are doing more complex things, you might like 'rx', which
> allows you to write regular expressions in S-expression syntax,
> thus giving you access to template macros and all that goodness.

This is a task for rx indeed - or rx-to-string when the regexp depends
on the run-time value of a variable:

(let ((ntimes 8))
  (re-search-forward
   (rx-to-string `(= ,ntimes "hello"))))


Michael.