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'

In reply to Re: Problem with capturing all matches with regex by dr3ad
in thread Problem with capturing all matches with regex by igoryonya

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.