Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
971 views
in Technique[技术] by (71.8m points)

regex - How to evaluate custom parenthesis expression in C#?

I am working on an Advanced Search feature where the expression I need to evaluate will look something like this with the parenthesis in place:

((Loan number is 1000 And
Lock Date is less than 12/03/2015) Or
Borrower SSN contains 12345) And
((Buy date is between 12/01/2015 and 23/02/2016 And
APR is less than 20000) Or
Loan amount is greater than 60000)

Or in simple words

((condition1 And condition2) Or condition 3) And ((condition4 And condition5) Or condition6).

If we look at the parenthesis, the condition1 and condition2 has to be evaluated first and then the output of this is executed with condition 3 and so on....

We have API to evaluate two conditions at a time. However the challenge in this context is

1) How to identify the corresponding parenthesis and evaluate them first. And then use this intermediate result for further evaluation?.

2)How to find unused parenthesis? For example (((condition1 And condition2))), in this case the though it is not required there are 3 starting and 3 closing parenthesis which is a valid expression.

I tried finding some algorithm here and here

However this takes token based manipulation which reads one character at a time and it is an arithmetic expression evaluation that computer understands. In my case these things are custom and we should find a algorithm to do this. Can anyone suggest a better approach for my scenario?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understand you correctly, you already got the expression evaluator. What you need is to split the evaluations according to the parenthesis. I'd use a loop, in which I'd find inner parenthesis groups, using this regex:

(([^()]*))

Then, if found, replace them with the result of your evaluation routine, and repeat until a final string remains, without parenthesis.

Pseudo code:

Find a string enclosed by (), not containing any ()
If found
    Replace it with the evaluated value of the string (including parenthesis)
    Go again
Return result

About the unused parenthesis, let them be treated the same. They'll end up in your evaluation routine as a single value.

Check this fiddle. Instead of evaluating it returns a random number, 0 or 1, but it demonstrates the logic.

Hope this helps.

Regards.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...