Parsing the Logical expression

Sometimes you need to parse the logical expression.

I have made for my own purposes the regular expression which would distringuish all important tokens from the logical expression:
([\(!\s]*)[\s]*([^<=\s]+)[\s]*(<>|!=|==|<=|>=|<|>)[\s]*([^\s&|\)]*)[\s]*([\)]*)(&&|\|\|)?
or as java string:
"([\\(!\\s]*)[\\s]*([^<=\\s]+)[\\s]*(<>|!=|==|<=|>=|<|>)[\\s]*([^\\s&|\\)]*)[\\s]*([\\)]*)(&&|\\|\\|)?"

this would give for

 !(! (one== 56) && two>45) || !three!=funny
the following solution
Regular Expression ([\(!\s]*)[\s]*([^<=\s]+)[\s]*(<>|!=|==|<=|>=|<|>)[\s]*([^\s&|\)]*)[\s]*([\)]*)(&&|\|\|)?
as a Java string "([\\(!\\s]*)[\\s]*([^<=\\s]+)[\\s]*(<>|!=|==|<=|>=|<|>)[\\s]*([^\\s&|\\)]*)[\\s]*([\\)]*)(&&|\\|\\|)?"
Replacement $1fieldValue(\"$2\")$3$4$5$6
groupCount() 6
Test Target String matches() replaceFirst() replaceAll() lookingAt() find() group(0) group(1) group(2) group(3) group(4) group(5) group(6)
1 !(! (one== 56) && two>45) || !three!=funny No !(! (fieldValue("one")==56) && two>45) || !three!=funny !(! (fieldValue("one")==56) && fieldValue("two")>45) || !fieldValue("three")!=funny Yes Yes !(! (one== 56) !(! ( one == 56 ) null
next find() Yes two>45) two > 45 ) null
next find() Yes !three!=funny ! three != funny null

Comments

shree said…
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -Jamie Zawinski

Popular posts from this blog

Exporting Skype Chat/Skype Contacts to csv file using the shell script and sqlite3 (usually already installed on mac)

trim() not supported by IE7 and IE8

Finally, clear explanation of TinyOS 2.x serial packet structure