Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to combine these two regular expressions

13 views
Skip to first unread message

Cecil Westerhof

unread,
Aug 12, 2012, 10:57:18 AM8/12/12
to
I was asked by someone for a regular expression that could combine
several search patterns, so that a file only needs to be scanned ones
and not several times. I was partly successful, but I still need two
passes.

I now have the following code:
(defun dcbl-search-heading ()
(interactive)
(re-search-forward "\\(.
\\)\\(

\\)\\(.+
\\)\\(
?.+
\\)" nil t)
(replace-match "\\1
#heading#
\\4"))

(defun dcbl-search-heading2 ()
(interactive)
(re-search-forward "\\(.
\\)\\(
\\)\\(.+
\\)\\(\\\(.+
\\\)+\\)" nil t)
(replace-match "\\1
#heading#
\\4"))

Is there a way to combine those regular expressions to one?

By the way, if the used expressions could be optimised, let me know. I
do not make them often, thus maybe I do things sub-optimal here.

--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof

Jambunathan K

unread,
Aug 12, 2012, 2:44:16 PM8/12/12
to Cecil Westerhof, help-gn...@gnu.org

You should provide a human-readable description of what the regexes are
trying to do. Have you tried:

C-h f regexp-opt RET

Doug Lewan

unread,
Aug 13, 2012, 10:08:26 AM8/13/12
to Cecil Westerhof, help-gn...@gnu.org
The most common way to "combine" two regular expressions is the form "\\(RE1\\|RE2\\)".

I usually do this with variables (concat "\\(" re-1 "\\|" re-2 "\\)").

There's also the form "\\(?:...\\)" if you don't care about match data or "\\(?N:...\\)" if you care very much about it. (N is an integer and forces this match to become match number N.)

I hope this helps.

,Doug
0 new messages