emacs-devel
[Top][All Lists]
Advanced

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

Re: A function to take the regexp-matched subsring directly


From: Philip Kaludercic
Subject: Re: A function to take the regexp-matched subsring directly
Date: Sun, 30 Oct 2022 17:29:21 +0000

Stefan Monnier <monnier@iro.umontreal.ca> writes:

>> +;;;###autoload
>> +(defun regexp-match (regexp string &optional n)
>> +  "Return the N -th matched substring for REGEXP in STRING.
>> +N defaults to 0 (the whole match).
>> +
>> +This function does not change the match data."
>> +  (declare (pure t) (side-effect-free t))
>> +  (let ((n (or n 0)))
>> +    (save-match-data
>> +      (when (string-match regexp string)
>> +        (match-string n string)))))
>
> `save-match-data` is costly and extremely rarely needed.

What makes it so expensive?  The implementation appears to be trivial.

> So I'd much rather not save it here.

If the function is supposed to be side-effect-free, then it ought not to
sometimes replace the match data and not touch it when optimised away.

>> +  (save-match-data
>> +    (when (string-match regexp string)
>> +      (let ((match-index (1- (/ (length (match-data)) 2)))
>> +            matches)
>> +        (while (<= 0 match-index)
>> +          (push (match-string match-index string) matches)
>> +          (setq match-index (1- match-index)))
>> +        matches))))
>
> I suspect it'd be more efficient to iterate directly on the `match-data` 
> rather
> than on an integer (which suffers from an O(N²) complexity).
>
>
>         Stefan



reply via email to

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