Cheeso
Cheeso

Reputation: 192447

emacs: Is it possible to match strings with balanced parens with emacs regex?

Something like this:
http://perl.plover.com/yak/regex/samples/slide083.html

In other words I want to match successfully on { { foo } { bar} } but not on { { foo } .

I see it's possible in perl, and in .NET. Is it possible in emacs regex?

Upvotes: 8

Views: 819

Answers (3)

Tobias
Tobias

Reputation: 31

If you are still interested have a look at cexp.el.

It is just a hack but maybe serves your purpose.

You can search for combined regular and balanced expressions with cexp-search-forward. The built-in re-search-forward is used for regular expressions and so its syntax rules apply. Balanced expressions can be matched with the additional syntax elements \!( and \!).

The most serious restriction is that balanced expressions may not occur in groups. So a construct like \!(^{ \(\!(^{.*}$\!)\)+ }$\!) does not work because of the group containing the inner balanced expression.

Nevertheless, one useful example is matching TeX-definitions like

\def\mdo#1{{\def\next{\relax}\def\tmp{#1}\ifx\next\tmp\else\def\next{#1\mdo}\expandafter}\next}

with combined expressions like

\\def\\[[:alpha:]]+\(#[0-9]\)*\!(^{.*}$\!)

The search via cexp-search-forward with the above cexp returns the limits for the following groups:

  1. The beginning and the end of the full match
  2. The limits of the match for the regular expression before the balanced expression, i.e. \def\mdo#1
  3. The limits of the captured group in the first regular expression, i.e., #1
  4. The limits of the balanced expression, i.e., {{\def\next{\relax}\def\tmp{#1}\ifx\next\tmp\else\def\next{#1\mdo}\expandafter}\next}

Upvotes: 2

Singletoned
Singletoned

Reputation: 5129

No, but if you have a particular use case to discuss you'll often find that you don't need regexes. Simple state-machines to match parenthases are pretty simple to write in lisp. Looking at the source of Paredit is a good place to start.

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

No, so far Perl/PCRE and .NET are the only regex flavors that support arbitrary nesting (recursive patterns).

Upvotes: 8

Related Questions