In case you're still curious:
"^[^\(\)]*(((?<OpenParen>\()[^\(\)]*)+((?<CloseParen-OpenParen>\))[^\(\)]*)+)*(?(OpenParen)(?!))$"
Example Code:
public class App1
{
[STAThread]
static void Main()
{
string pattern =
@"^[^\(\)]*(((?<OpenParen>\()[^\(\)]*)+((?<CloseParen-OpenParen>\))[^\(\)]*)+)*(?(OpenParen)(?!))$";
string[] inputs = {"( ( A * B ) / C) - 10 ", " ) ( A * B ( / C ( -
10", "( ( A * B / C) - 10 ", "()", "(()", "(()))"};
foreach(string input in inputs)
{
Match m = Regex.Match(input, pattern);
if(m.Success)
{
Console.WriteLine("Input: \"{0}\" \nMatch: \"{1}\"", input, m);
}
else Console.WriteLine("Input: \"{0}\" did not match.", input);
}
}
}
That worked perfectly. I was just checking in the wrong place.
THANKS!!
cbmeekshttp://
www.codershangout.com
(e-mail address removed) wrote:
cbmeeks wrote:
Thanks! That is an excellent idea.
However, the following is returning OK:
( ) ) (
because it is zero.
I think after I pass the first check I will go through and do the
other
check mentioned earler
cbmeeks
http://www.codershangout.com
rossum wrote:
On 8 Dec 2006 09:50:17 -0800, "cbmeeks" <
[email protected]>
wrote:
I have a project that requires me to validate the syntax of
basic math
formulas.
Something like: ( ( A * B ) / C) - 10
I need to just make sure that parenthesis are correct.
For example, you cant have a formula like: ) ( A * B ( / C ( -
10
Checking for equal number of ( as ) is easy.
Thanks!
cbmeeks
http://www.codershangout.com
No need for a regular expression if you are just checking
parentheses.
Start a count at 0. Every time you hit '(' increment the count.
Every time you hit ')' decrement the count. If the count goes
negative then you have a ')' before its corresponding '('. If
the
count is not zero at the end of the expression then you have a
'('
without a corresponding ')'. If the count is zero at the end of
the
expression then the parentheses are well formed.
rossum
Add the condition that the "count" must never be less than zero as it
scans. Your example of ( ) ) ( will be negative -1 before it hits the
end, specifically just after the second ')' character.