你可以用一个条件来做到这一点:
if (Regex.IsMatch(subject,
@"^ # Start of string
( # Match and capture into group 1:
\( # an opening parenthesis
)? # optionally.
[^()]* # Match any number of characters except parentheses
(?(1) # Match (but only if capturing group 1 participated in the match)
\) # a closing parenthesis.
) # End of conditional
$ # End of string",
RegexOptions.IgnorePatternWhitespace)) {
// Successful match
}
或者,当然,因为字符串只有两种匹配方式:
if (Regex.IsMatch(subject,
@"^ # Start of string
(?: # Either match
\( # an opening parenthesis,
[^()]* # followed by any number of non-parenthesis characters
\) # and a closing parenthesis
| # or
[^()]* # match a string that consists only of non-parens characters
) # End of alternation
$ # End of string",
RegexOptions.IgnorePatternWhitespace))