perl regexp problem
i have these kind of lines
object1:object2:object3:rest of the line
I want a regular expression for extracting each text until the colon.
In this case I need:
$1= object1 $开发者_JAVA百科2= object2 $3= object3 $4= rest of the line
I tried with this:
$_ =~ m/\(.*\):\(.*\):\(.*\):\(.*\)/i
but it seems to not work.
where am I wrong?
Why are you using a regex for this when split
does exactly what you want?
$x = "object1:object2:object3:rest of the line";
@x = split (":", $x);
foreach $s (@x) {
print "$s\n";
}
This outputs:
object1
object2
object3
rest of the line
If you want to limit yourself to four fields regardless of the number of colons, you can use:
$x = "object1:object2:object3:rest of the line with a : character";
@x = split (":", $x, 4);
foreach $s (@x) {
print "$s\n";
}
which outputs:
object1
object2
object3
rest of the line with a : character
You need to remove the \
's:
$_ =~ m/(.*?):(.*?):(.*?):(.*)/i
Also, the i
(case-insensitive matching) is redundant since you have no characters in your regex as well as the m
which allows you to choose a different regex boundary character other than /
. You also don't need the $_ =~
as Perl defaults to $_
. So you can reduce it to:
/(.*):(.*):(.*):(.*)/
http://ideone.com/TLepM
my @objects = split ':', $data_line, 4;
精彩评论