One possible way:

c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my $s = q{name1=value1 name2=' value2=0' name3=value3}; ;; my $name = qr{ \w+ }xms; my $plain = qr{ \w+ }xms; my $s_quoted = qr{ ' [^\x27]* ' }xms; ;; my %h = $s =~ m{ ($name) \s* = \s* ($s_quoted | $plain) \s* }xmsg; dd \%h; " { name1 => "value1", name2 => "' value2=0'", name3 => "value3" }
Please see perlre, perlrequick, and perlretut.

Updates:

  1. Note that  \x27 in  [^\x27] represents a  ' (single-quote) character. I have to use this form because my REPL does not like unbalanced single-quotes in a command-line code expression. You can use  [^'] like a sane person.
  2. Another and probably better approach would be to forget regexes and use Text::CSV or Text::CSV_XS.
  3. If you need to get rid of the single-quotes and have Perl version 5.10+, try this. Note that  $s_quoted is changed and the  m// match uses  (?|pattern) from Extended Patterns.
    c:\@Work\Perl>perl -wMstrict -MData::Dump -le "use 5.010; ;; my $s = q{name1=value1 name2=' value2=0' name3=value3}; ;; my $name = qr{ \w+ }xms; my $plain = qr{ \w+ }xms; my $s_quoted = qr{ [^\x27]* }xms; ;; my %h = $s =~ m{ ($name) \s* = \s* (?| ' ($s_quoted) ' | ($plain)) \s +* }xmsg; dd \%h; " { name1 => "value1", name2 => " value2=0", name3 => "value3" }
    If you don't have 5.10, let me know. There's a simple alternative.


Give a man a fish:  <%-(-(-(-<


In reply to Re: parse string containing space by AnomalousMonk
in thread parse string containing space by mtovey

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.