Kerby82
Kerby82

Reputation: 5146

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 $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?

Upvotes: 1

Views: 111

Answers (3)

paxdiablo
paxdiablo

Reputation: 881123

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

Upvotes: 4

FMc
FMc

Reputation: 42411

my @objects = split ':', $data_line, 4;

Upvotes: 1

moinudin
moinudin

Reputation: 138317

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

Upvotes: 3

Related Questions