Jump to content

Regex to break apart math equations


Recommended Posts

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

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

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
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.