Valid:
((int)10)
(int)10
((char)((x+y)&1))
((int *)1)
Invalid:
This statement:
The language of (balanced) parenthesized expressions is not regular, i.e., you can't write a regular expressions matching these kind of strings.
is true only of classic regular expressions in the pathologically formal sense. It does not apply to the practical patterns which many of us use daily.
For example, using the third string from the original list of valid inputs, this Perl code:
my $str = "((char)((x+y)&1))";
my $w = length length $str ;
my $rx = qr{ (?
\(
(?:
[^()] +
|
(?&PAREN)
) *
\)
)
}x;
while ($str =~ /(?=$rx)/g) {
printf "Matched from %*d to %*d: %s%s\n" =>
$w => pos($str),
$w => pos($str) + length($+{PAREN})-1,
" " x pos($str) => $+{PAREN};
}
quite handily produces the following output:
Matched from 0 to 16: ((char)((x+y)&1))
Matched from 1 to 6: (char)
Matched from 7 to 15: ((x+y)&1)
Matched from 8 to 12: (x+y)
I can't tell from eyeballing the original set of inputs just what it is that makes one valid and the other invalid. Still, I'm sure some elaboration of the code I gave above will work perfectly fine.
However, you will have to write it in Perl, as Java's patterns just aren't powerful enough. ☹