Capture parens will only return one value per application of the regex. Your try has three sets, so it will return three values, no matter how many times that *? repeats.
To do what you want, you need the //g flag:
$x="[x=1 y=3 z=5]";
print join ":", $x=~/(\w+)=(\d+)/g;
That just skips over the [, ], and spaces around your = pairs.
The above will treat foo-bar=5 as bar=5, ignoring the "foo-" since it has a non-\w char.
To know that your regex is parsing the complete string successfully, do it like this:
print join ":", $x=~/\G # start where prev match left off
(?:\A\[)? # if start of string, expect [
(\w+)=(\d+) # our data
(?:\s(?!\z) # between pairs, expect \s
|\]\z) # or if end of string, expect ]
/gcx;
# if whole string was parsed, pos will be defined and equal to length
print "error" unless pos($x) && pos($x) == length($x);
This is a very useful idiom (to me anyway). It looks fairly complicated at first, but once you go through and understand it, you can see that most of it stays the same for different applications. You just replace the first \[, the data line, the \s, and the last \[ as appropriate for what you are parsing.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.