in reply to Problem with capturing all matches with regex
The original question did not request the equation's result (the part after the '=' sign). A solution to that is retained at the bottom of this comment.
The updated question does (I missed that). In case someone is searching for something similar, where the intent is to get the separate components of the equation into an array, here is one way to capture the parts of the equation into an array without extraneous whitespace in the array values, without attaching operators to operands, and also keeping the '=' sign rather than inferring it.
my $equation = '979x + 87y - 8723z = 274320'; my $vars = 'xyz'; my $operators = qr/[-+*\/%=]/; my @parts = $equation =~ /([^\s$vars]+|[$vars]|$operators)/g;
perl -d DB<1> $equation = '979x + 87y - 8723z = 274320' DB<2> $vars='xyz' DB<3> $operators=qr/[-+*\/%=]/ DB<4> x $equation =~ /([^\s$vars]+|[$vars]|$operators)/g 0 979 1 'x' 2 '+' 3 87 4 'y' 5 '-' 6 8723 7 'z' 8 '=' 9 274320
Here is a solution for the original, non-updated, question that eliminates the equation's result. It captures one of these two strings: 1. Anything that is not an x, y, or z that is followed by an x, y, or z. 2. An x, y, or z.
Requiring what is captured in (1) to be followed by an x, y, or z prevents ' = 274320' from being captured.
my @parts = $equation =~ /([^xyz]+(?=[xyz])|[xyz])/g;
perl -d DB<1> $_='979x + 87y - 8723z = 274320' DB<2> x /([^xyz]+(?=[xyz])|[xyz])/g 0 979 1 'x' 2 ' + 87' 3 'y' 4 ' - 8723' 5 'z'
|
|---|