note
haukex
<p>Although personally I'd still use a conditional, of course it's possible to do it all in one regex. One way is by making the comma optional by putting a <c>?</c> on a group, in this case I'm using a non-capturing <c>(?:...)</c> group, and I had to make the first part of the regex non-greedy so that it doesn't swallow an existing comma:</p>
<c>
use warnings;
use strict;
use Test::More;
my $regex = qr/ ^ (.*?) (?: , ([^,]*) )? $ /x;
ok "abc"=~$regex;
is $1, "abc";
is $2, undef;
ok "abc,5"=~$regex;
is $1, "abc";
is $2, 5;
ok "a,b,c,5"=~$regex;
is $1, "a,b,c";
is $2, 5;
done_testing;
</c>
<p><i>Update:</i> An alternative that says a little more explicitly: either match a string with <i>no</i> commas in it, <i>or</i>, if there are commas, I want to match the thing after the last one: <c>/^ (?| ([^,]*) | (.*) , ([^,]*) ) $/x</c> <i>Update 2:</i> And it turns out this regex is much faster than the above! (try using it in [id://1215457|this benchmark])</p>
1215361
1215377