in reply to Perl is returning... odd results... from regular expressions. Things matching when they shouldn't, and stuff like that.

split /(\".*?\"(?=,))|(.*?(?=,))|(.*?(?=\n))/
/(?=,)/ is a lookahead: it looks at the comma, but it doesn't include it in the match. That's why it's not at the end of the matched strings. Nowhere do you get rid of the commas, so they still appear at the start of the next match, which is a problem: your doublequoted strings will never be recognized after the first match, because of this comma!

Also, I'm not convinced your use of split is the best advice. Why not use //g?

$_ = qq(item1,field2,more data,"a quoted, comma containing string"\n); @data = /(\".*?\"|.*?)[\n,]/g; $j = 0; printf "%d: %s\", $j++, $_ for @data;
Result:
0: item1 1: field2 2: more data 3: "a quoted, comma containing string"

p.s. I didn't use this, but you're probably better off testing with defined than with a truth value to weed out unused captures.

  • Comment on Re: Perl is returning... odd results... from regular expressions. Things matching when they shouldn't, and stuff like that.
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: Perl is returning... odd results... from regular expressions. Things matching when they shouldn't, and stuff like that.
by Groxx (Novice) on Jan 11, 2007 at 20:55 UTC
    Nowhere do you get rid of the commas, so they still appear at the start of the next match, which is a problem: your doublequoted strings will never be recognized after the first match, because of this comma!

    Actually, I was having that problem as well, and that explains it nicely. Thanks! I'll give your code a try as well.