views:

224

answers:

3

I found some interesting possibility in many regex engines:

It's possible to place backreference inside the capture group and reference this group.

For example: (\1)

My question: for what regex patterns it may be used? I can't imagine...

A: 

Consider this sample:

[something] some text [something]

You can use backreferences this way:

(\[something\])(.*?)\1
Rubens Farias
+3  A: 

There is an explanation for use of nested references, which I think clearly demonstrates the marginal usefulness of this feature.

SilentGhost
Example regex, please.
ControlFlow
If you sloooowly read my question, you'll understand that I'm not asking about how backreferences are used normally. Take a look WHERE backreference were placed in the example regex I provide.
ControlFlow
@ControlFlow: I don't see you posting *any* regex. I can't imagine what `(\1)` could possibly match or be useful for, or even compile. is this question limited to .net? if not, do provide us with some actual examples.
SilentGhost
`(\1)` does compile on .NET, but I am yet to find any possible use for it.
Max Shawabkeh
@SilentGhost The `(\1)` regex was the minimal example, not useful at all, just to demonstrate what I'm talking about. Thanks for the link, I've expecting the usefullness... Thank you!
ControlFlow
A: 

How about this (ignore the whitespace):

{ .* ( { .* \1 .* } ) .* }

to match the body of a method in C#/Java/...

d0rk
It will not work, backreference matches with the capture group 1 matched text, not the pattern in the group 1 itself.
ControlFlow