Link: http://topic.csdn.net/t/20051227/16/4484337.html
RegEx = new RegEx (@"
^ (? # Match the beginning)
[-+]? (? # Positive and negative numbers can appear at the beginning)
([0-9] + ($ | [-+ */]) * (? # Optional number-symbol -...... -Number-symbol or end)
(
(
(? <O> \()(? # Left brackets, saved to the O name)
[-+]? (? # Optional plus or minus signs)
([0-9] + [-+ */]) * (? # Optional number-character-number-character ......)
) + (? # The left parenthesis can be repeated)
[0-9] + (? # At least one operand is required between the left and right parentheses)
(
(? <-O> \))(? # Right brackets. Remove a left bracket when matching)
([-+ */] [0-9] + )*(? # Optional characters-number-character-number ......)
) + (? # You can repeat the right brackets, only if there are left parentheses left)
($ | [-+ */]) (? # Either end or an operator appears before the next left parenthesis)
)*(? # Repeated left brackets)
(? (O )(?!)) (? # If there are left parentheses, nothing will match)
(? <= [0-9)]) (? # Check whether there are digits or parentheses before the end)
$ (? # Matching end)
", Regexoptions. ignorepatternwhitespace );
String [] tests = new string [] {
"1 ",
"1 + 23 ",
"1 + 23*456 ",
"1*(23 + 456 )",
"(3 )",
"(67 + 8) * 9 + 10)/11 ",
"12 + (13 *)",
"()",
"(3 )",
"(3 ))",
"+ 3 ",
"5*(4 + 3/(-2 ))",
"(5*(4 + 3/(-2 ))",
"5*(4 + 3/(-2 )))",
"+ 3 *",
"+ (4) + (-5 )",
"+ (4) (5 )",
};
Foreach (string s in tests)
Console. writeline ("{0 }:{ 1}", RegEx. ismatch (s )? "Good": "bad", S );
Console. readkey ();
The complete regular expression should be: ^ [-+]? ([0-9] + ($ | [-+ */]) * (? <O> \ () [-+]? ([0-9] + [-+ */]) *) + [0-9] + ((? <-O> \) ([-+ */] [0-9] +) *) + ($ | [-+ */]) * (? (O )(?!)) (? <= [0-9)]) $ # C # column