Jump to content

Regex to break apart math equations


Recommended Posts

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

Link to comment
Share on other sites

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 “.” «.»

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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
)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.