Reputation: 6259
how to extract this string using regular expression
||03/15/2012||10:17:11|FOR TEST
I want to extract "03/15/2012" . I have tried this command
my $firstLine =~ m/^\|\|\d{2}\/\d{2}\/\d{4}\|\|/i ;
trace("first line extraction : $firstLine first $1");
It doesn't work. could you please help ?
thanks
Upvotes: 1
Views: 141
Reputation: 93056
You can assign the value of the a capturing group directly like this:
my $in = "||03/15/2012||10:17:11|FOR TEST";
(my $Date) = $in =~ /^\|\|(\d{2}\/\d{2}\/\d{4})\|\|/;
You will find the result of the capturing group 1 in $Date
.
Btw. you don't need the modifier i
, because this makes letters matching case insensitive, since you have no letters in your regex, this option is useless.
Upvotes: 1
Reputation: 43703
Script:
my $firstLine = '||03/15/2012||10:17:11|FOR TEST';
print $1 if $firstLine =~ /(\d{2}\/\d{2}\/\d{4})/;
Output:
03/15/2012
Test this code here: http://ideone.com/99iUg
Upvotes: 0
Reputation: 364
Try: my $firstLine =~m/^\|\|(.+)\|\|.*$/i
You only really care about what's between the first two sets of double pipes
Upvotes: 0
Reputation: 156652
You need to use a capturing group ()
around the part you want to extract:
my $line = '||03/15/2012||10:17:11|FOR TEST';
if ($line =~ m/^\|\|(\d{2}\/\d{2}\/\d{4})\|\|/i) {
# Capturing group ┴───────────────────┘
print("Group 1: $1\n"); # 03/15/2012
}
Upvotes: 4