I have input string in following format(It may possible that after closing brackets space can be present).
(1, 'c21bd4d76fe97759aa27a0c99bff6710')
I want to extract number and id into different variables, how should I go about it?
I have tried following approach but I wanted something that will work with regex because extra space after input string breaks my solutions.
$text = "(1, 'c21bd4d76fe97759aa27a0c99bff6710')";
my @parts = split(/,/,$text);
my $rowd_id = substr(@parts[0],1);
my $id = substr(@parts[1],2,-2);
print "$rowd_id $id\n";
CodePudding user response:
You can use capture group in a regex:
my $text = "(1, 'c21bd4d76fe97759aa27a0c99bff6710')";
my $re = qr/\(\h*(\w )\h*,\h*'([^'] )'/;
my @captured = $text =~ $re;
if( @captured ) {
my $rowd_id = @captured[0];
my $id = @captured[1];
print "$rowd_id :: $id\n";
}
Output:
1 :: c21bd4d76fe97759aa27a0c99bff6710
RegEx Details:
\(
: Match a(
\h*
: Match 0 or more whitespaces(\w )
: Match 1 word characters in capture group #1\h*
: Match 0 or more whitespaces,
: Match a,
\h*
: Match 0 or more whitespaces'
: Match a'
([^'] )
: Match 1 of any characters that is not'
in capture group #2'
: Match a'