regexes with balancing group definitions

  • Thread starter Thread starter Arnshea
  • Start date Start date
A

Arnshea

There's an article (well, an editor's update to an article - at
http://msdn.microsoft.com/msdnmag/issues/04/06/NETMatters/#edupdate )
that presents the following regular expression for detecting balanced
brackets.

string pattern =
@"^((?<openBracket>\{) | [^\{\}] |" +
@"(?<closeBracket-openBracket>\}))*" +
@"(?(openBracket)(?!))$";

What is the purpose of the last line? Shouldn't

^((?<openBracket>\{) | [^\{\}] | (?<closeBracket-openBracket>\}))*$

be sufficient?
 
Hello Arnshea,
There's an article (well, an editor's update to an article - at
http://msdn.microsoft.com/msdnmag/issues/04/06/NETMatters/#edupdate )
that presents the following regular expression for detecting balanced
brackets.

string pattern =
@"^((?<openBracket>\{) | [^\{\}] |" +
@"(?<closeBracket-openBracket>\}))*" +
@"(?(openBracket)(?!))$";
What is the purpose of the last line? Shouldn't

^((?<openBracket>\{) | [^\{\}] | (?<closeBracket-openBracket>\}))*$

be sufficient?

That last line looks completely unneeded to me. It might be done to make
sure that openBracket must match a new string, before a matching close bracket
is found again.... (?!) will never match.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top