smerny Posted June 7, 2011 Share Posted June 7, 2011 Hello, how would I break apart a math equation such as... "(124-55)*(12+5)" into something like into an array containing: (, 124, -, 55, ), *, (, 12, +, 5, ) basically break everything up except groupings of numbers? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/238685-regex-to-break-apart-math-equations/ Share on other sites More sharing options...
xyph Posted June 7, 2011 Share Posted June 7, 2011 Interesting... Try this one. It allows for decimals as well ([^\d.]|[\d.]++) And in English ([^\d.]|[\d.]++) Match the regular expression below and capture its match into backreference number 1 «([^\d.]|[\d.]++)» Match either the regular expression below (attempting the next alternative only if this one fails) «[^\d.]» Match a single character NOT present in the list below «[^\d.]» A single digit 0..9 «\d» The character “.” «.» Or match regular expression number 2 below (the entire group fails if this one fails to match) «[\d.]++» Match a single character present in the list below «[\d.]++» Between one and unlimited times, as many times as possible, without giving back (possessive) «++» A single digit 0..9 «\d» The character “.” «.» Quote Link to comment https://forums.phpfreaks.com/topic/238685-regex-to-break-apart-math-equations/#findComment-1226560 Share on other sites More sharing options...
smerny Posted June 7, 2011 Author Share Posted June 7, 2011 hmmm.. either i'm doing this wrong or the regex isnt working (yea i'm using java btw) Pattern pattern = Pattern.compile("([^\\d.]|[\\d.]++)"); String[] equation = pattern.split("5+3+323"); System.out.println(equation.length); for (int i=0; i<equation.length; i++) System.out.println(equation[i]); edit: forgot to describe... array length is 0 Quote Link to comment https://forums.phpfreaks.com/topic/238685-regex-to-break-apart-math-equations/#findComment-1226572 Share on other sites More sharing options...
xyph Posted June 8, 2011 Share Posted June 8, 2011 Well, I can't help you with Java. Try storing the expression and echoing it out to make sure it matches. In PHP <?php $math='51*(23.5+14)/67'; $expr = '/[^\d.]|[\d.]++/'; preg_match_all( $expr, $math, $return ); echo "For $math using $expr\n"; print_r( $return[0] ); ?> Output For 51*(23.5+14)/67 using /[^\d.]|[\d.]++/ Array ( [0] => 51 [1] => * [2] => ( [3] => 23.5 [4] => + [5] => 14 [6] => ) [7] => / [8] => 67 ) Quote Link to comment https://forums.phpfreaks.com/topic/238685-regex-to-break-apart-math-equations/#findComment-1226839 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.