hi all,
i'm working on a regular expression that will match an arithmetic expression like 3+4/5, with valid operators being -,+,*,/ without negative numbers and decimal numbers being either abc. or .abc or abc.def in form. i first match the first number and then match the rest of the expression by capturing a pair: one operator then any number of digits. i'm currently working with php and my ultimate goal is to validate the string and evaluate the arithmetic expression.
/[+-\/*]\d+(\.\d*)?/
is my regular expression within preg_match and it seems to work for the most part. i'm assuming that the character class [+-\/*] will always match one of the four operators once and only once.
preg_match("/[+-\/*]\d+(\.\d*)?/", $str, $words, PREG_OFFSET_CAPTURE, $index);
but when i actually run the program, i find that the regular expression sometimes doesn't capture the operator with this test case: 89067/8+0.9+.8+9. (including the trailing decimal/period)
Array
(
[0] => 89067
[1] => 0
)
Array
(
[0] => Array
(
[0] => /8
[1] => 5
)
)
Array
(
[0] => Array
(
[0] => +0.9
[1] => 7
)
[1] => Array
(
[0] => .9
[1] => 9
)
)
Array
(
[0] => Array
(
[0] => .8
[1] => 12
)
)
Array
(
[0] => Array
(
[0] => +9.
[1] => 14
)
[1] => Array
(
[0] => .
[1] => 16
)
)
notice that the second to last line has the expression matching ".8" with the operator omitted. is there something i'm missing?