A regular expression is required: it must match the following patterns

Really:

  • ((int)10)
  • (int)10
  • ((char)((x+y)&1))
  • ((int *)1)

Invalid:

  • (a-b)
  • (a&=b)
  • a
  • ((a))
+1
source share
3 answers

The language of (balanced) expressions in parentheses is not regular , i.e. you cannot write regular expressions matching these string types.

See the SO Question: why regular expressions are called "regular" expressions and Wikipedia: Regular Languages .

You need to work with more capable parsing, such as CFG, such as ANTLR .

You can start with something like:

CastedExpression ::= Cast Expression | LPAR CastedExpression RPAR
Cast             ::= LPAR Type RPAR
Expression       ::= Sum | Product | Litteral | LPAR Expression RPAR | ...
Type             ::= char | int | Type ASTERISK | ...

(Feel free to edit the grammar above if you find any obvious improvements).

+8

:

() , .. , .

. , .

, , Perl:

my $str = "((char)((x+y)&1))";
my $w   = length length $str ;
my $rx  = qr{ (?<PAREN>
                \(
                   (?:
                       [^()] +
                     |
                       (?&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};
}

:

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)

, , , . , , , , .

Perl, Java . ☹

+1

Adding an answer to aioobe:

It sounds like you're trying to write an expression parser. As mentioned in another answer, using a regular expression is not possible. You should consider using an expression parser such as JEP, or write it yourself using javacc.

0
source

Source: https://habr.com/ru/post/1786028/


All Articles