Regex required: It should match for following patterns

后端 未结 3 1980
遇见更好的自我
遇见更好的自我 2021-01-25 11:25

Valid:

  1. ((int)10)
  2. (int)10
  3. ((char)((x+y)&1))
  4. ((int *)1)

Invalid:

3条回答
  •  死守一世寂寞
    2021-01-25 11:43

    The language of (balanced) parenthesized expressions is not regular, i.e., you can't write a regular expressions matching these kind of strings.

    See SO question: Why are regular expressions called "regular" expressions and Wikipedia: Regular Languages.

    You need to work with a more capable parsing technique such as a CFG with for instance ANTLR.

    You could 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 grammar above if you find any obvious improvements).

提交回复
热议问题