问题
I need to identify top-level expression from a given string and convert it into the left operand, right operand and operator in groovy.
I have created a matcher array to match expression and logic is as follow
static CONDITION_REGEXPS = [
'(.+) (==) (.+)',
'(.+) (!=) (.+)',
'(.+) (>) (.+)',
'(.+) (>=) (.+)',
'(.+) (<) (.+)',
'(.+) (<=) (.+)'
]
static fromString(def string) {
if (string) {
string = string.split('\\|\\|');
List<List> list = string.collect({
it.trim().replaceAll(/^\(|\)$/, '').split('&&').collect({ condition ->
condition = condition.trim()
def regex = CONDITION_REGEXPS.find({ condition.matches(it) })
if (regex) {
return [leftOperand: condition.replaceFirst(regex, '$1'), operator: condition.replaceFirst(regex, '$2'), rightOperand: condition.replaceFirst(regex, '$3')]
}
})
})
return list
} else {
return []
}
}
Now I am passing string into following function,
def str = '( ${a < b ? a : b} < ${a > b ? a : b} )'
println fromString(str);
Which given me wrong result,
leftOperand: ${a < b ? a : b} < ${a
operator: >
rightOperand: b ? a : b}
Which is wrong, it should be,
leftOperand: ${a < b ? a : b}
operator: <
rightOperand: ${a > b ? a : b}
Any help would be appreciated
来源:https://stackoverflow.com/questions/60796886/expression-not-correctly-identified-operators-and-operands