Expression not correctly identified ( Operators and Operands )

白昼怎懂夜的黑 提交于 2020-03-25 18:23:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!