Theoretical answer
Short answer:
What you're looking for is not possible using regular expressions.
Long Answer:
Regular expressions (as their name suggests) are a compact representation of Regular languages (Type-3 grammars
in the Chomsky Heirarchy).
What you're looking for is not possible using regular expressions as you're trying to write out an expression that maintains some kind of count (some contextual information other than beginning
and end
). This kind of behavior cannot be modelled as a DFA(actually any Finite Automaton). The informal proof of whether a language
is regular
is that there exists a DFA that accepts that language. As this kind of contextual information cannot be modeled in a DFA, thus by contradiction, you cannot write a regular expression for your problem.
Practical Solution
my ($lhs,$rhs) = $test =~ /^[^-]+-[^-]+-([^-]+)-([^-.]+)\S+/;
# Alernatively and faster
my (undef,undef,$lhs,$rhs) = split /-/, $test;
# Rest is common, no matter how $lhs and $rhs is extracted.
my @left = reverse split //, $lhs;
my @right = split //, $rhs;
my $i;
for($i=0; exists($left[$i]) and exists($right[$i]) and $left[$i] =~ /\d/ and $right[$i] =~ /\d/ ; ++$i){}
--$i;
$lhs= join "", reverse @left[0..$i];
$rhs= join "", @right[0..$i];
print $lhs, "\t", $rhs, "\n";
s/.*(\d{2})-(\d{2}).*//
– GreatBigBore 13 hours agoxyz45sd2-32d34-sd23-1d3f5b.abc.com
? Would you expect3
and1
? – Samveen 9 hours ago