Reputation: 19857
for a factoring program I'm making I'm wondering if anyone can help me out.
Say I have an equation like
5x^2 + 3x + 7
I need to isolate 5, 3 and 7
although it could come up with negative signs are oppose to positive signs aswell.
Is there any efficient regex that would do it? as the way I'm doing it right now is fairly long and not very efficient.
Upvotes: 2
Views: 69
Reputation: 13765
The best way would be to parse it via constructing an expression tree (just like a compiler would). Note that regular expressions or splits won't account for operator precedence, such as (2 + x)^2
Basically 5x^2 + 3x + 7 should be parsed as
+
/ \
+ 7
/ \
* *
/ \ / \
5 ^ 3 x
/ \
x 2
However, if you can assume format such as an x^n + a(n-1) x^(n-1) + ... a1 x + a0
then you can just remove everything you don't need, you can try this
$string = '5x^2 + 3x + 7';
$replace = '';
$pattern = '/x(\^(\d)*)?/';
echo preg_replace( $pattern, $replacement, $string );
// echos 5 + 3 + 7;
You should be able to take from there, e.g.
$stripped = preg_replace( $pattern, $replacement, $string );
$modified = str_replace( array( '+', '-' ), '|', $stripped );
$parts = explode( '|', $modified );
print_r( $parts );
// should be array( 5, 3, 7 );
Upvotes: 3
Reputation: 152304
Try with following regex:
(?:^|[^\^])((?:\- *)?\d+)
Combine it with preg_match_all
function.
Explanation:
It matches all digits
(\d+)
with optional negative sign (whitespacesbetween allowed)
(?:\- *)?
that are not followed with ^
sign
[^\^]
or are on the beggining of the string
^
(so there is ^|[^\^]
) matched in non-captured group
(?:^|[^\^])
Upvotes: 3