Validate a Boolean expression with brackets in C#

后端 未结 6 679
清歌不尽
清歌不尽 2021-01-18 01:12

I want to validate a string in C# that contains a Boolean expression with brackets. The string should only contain numbers 1-9, round brackets, \"OR\" , \"AND\".

Exa

6条回答
  •  我在风中等你
    2021-01-18 02:06

    Pretty simply:

    At first stage you must determ lexems (digit, bracket or operator) with simple string comparsion.

    At second stage you must define variable of count of closed bracket (bracketPairs), which can be calculated by the following algorithm for each lexem:

    if current lexem is '(', then bracketPairs++;

    if current lexem is ')', then bracketPairs--.

    Else do not modify bracketPairs.

    At the end if all lexems are known and bracketPairs == 0 then input expression is valid.

    The task is a bit more complex, if it's necesery to build AST.

提交回复
热议问题