Evaluate String as a condition Java

2019-01-07 21:08发布

I have to retrieve a set of column values from D/B and check it as a condition.

For example, I will have strings like "value > 2", "4 < value < 6" in a D/B column. (value is the one which is compared all the time). I will have a variable value declared in my code and I should evaluate this condition.

int value = getValue();
if (value > 2)  //(the string retrieved from the D/B)
  doSomething();

How can I do this?? Any help is muceh appreciated. Thanks.

8条回答
一纸荒年 Trace。
2楼-- · 2019-01-07 21:41

You should try parsing the string inside the if statement by doing something like

if(parseMyString(getValue()))
    doSomething();

In parseMyString can determine what you need to evaluate for the condition. If you don't know how to create a parser then take a look at: http://www.javapractices.com/topic/TopicAction.do?Id=87

查看更多
我命由我不由天
3楼-- · 2019-01-07 21:44

You are basically evaluating a scripted expression. Depending what is allowed in that expression, you can get away with something very simple (regular expression identifying the groups) or very complex (embed a javascript engine?).

I'm assuming you're looking at the simple case, where the expression is: [boundary0] [operator] "value" [operator] [boundary1]

Where one, but not both of the [boundary] [operator] groups might be omitted. (And if both are presents, operator should be the same)

I would use a regular expression for that with capturing groups.

Something like: (?:(\d+)\s*([<>])\s*)?value(?:\s*([<>])\s*(\d+))?

And then: boundary1 = group(1); operator1 = group(2); operator2 = group(3); boundary2 = group(4)

查看更多
登录 后发表回答