my $g = { space => qr/\x20+/o, trailing_space => qr/\x20*/o, }; my $irc_regex = qr/^ (?: \x3a # : comes before hand (\S+) # [prefix] $g->{'space'} # Followed by a space )? # but is optional. ( \d{3}|[a-zA-Z]+ # [command] ) # required. (?: $g->{'space'} # Strip leading space off [middle]s ( # [middle]s (?: [^\x00\x0a\x0d\x20\x3a] [^\x00\x0a\x0d\x20]* ) # Match on 1 of these, (?: $g->{'space'} [^\x00\x0a\x0d\x20\x3a] [^\x00\x0a\x0d\x20]* ){0,13} # then match on 0-13 of these, ) )? # otherwise dont match at all. (?: $g->{'space'}\x3a # Strip off leading spacecolon for [trailing] ([^\x00\x0a\x0d]*) # [trailing] )? # [trailing] is not necessary. $g->{'trailing_space'} $/x;