Click to See Complete Forum and Search --> : how to print a matched pattern
andre
03-07-2004, 09:13 PM
in perl, I open a file
the file has entries like 0:00:01.992 0:00:00.630 5080 2045 2468 8 81 2 1368.
I'm able to match the patern I'm interested in, which is the first set of numbers with /[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]/
but I can't figure out how to print the matched patern, and not the whole line. can anyone give me a hand?
blackrax
03-07-2004, 09:29 PM
well - i'm a perl virgin, but if i remember correctly, isn't it something like.
"s/^\([0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]\).*$/\1/g"
not sure if you have to escape the brackets in perl though, but if you suddenty end up with no matches, remove the "\" before the brackets.
cheers,
//blackrax
edit: what the regular expression does, or is meant to do, is to assign a group (in this case, your original pattern) and replace the line/string with that group... and if you want to simplify your expression, try
"s/^\([^ ]*\).*$/\1/g"
dchidelf
03-09-2004, 05:22 PM
The string matching each regex within ()'s will be assigned to $n, where n indicates which set of ()'s.
if /((blah1)(blah2))/ matched a string
$1 = "blah1blah2"
$2 = "blah1"
$3 = "blah2"
/([0-9][0-9]:[0-9][0-9]\.[0-9][0-9][0-9])/;
print "$1\n";
OR
/([0-9][0-9]):([0-9][0-9])\.([0-9][0-9][0-9])/;
print "$1:$2.$3\n";
flukshun
03-09-2004, 05:44 PM
you can store matches to a variable using () within the regex. assuming you are looping through lines of a file, using your match pattern it would look like this:
while (<FILEHANDLE>) {
if (/([0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9])/) {
print $1;
}
}
but your regex looks odd, and if i'm not mistaken it wont match any strings that begin with a single digit number. for instance, your example "0:00:01.992 0:00:00.630 5080 2045 2468 8 81 2 1368." would fail because the beginning "0:" wont match the "[0-9][0-9]:" Also, "\d" can be substituted for "[0-9]", and looks much better. Also, "^" will anchor the match to the beginning of the line to avoid any false matches.
rather than point it all out i should probably refer you to "perldoc perlretut", it's an excellent tutorial.
but this should do what you need:
while (<FILEHANDLE>) {
if (/^(\d?\d:\d\d:\d\d.\d+)/) {
print $1;
}
}
/^(\d?\d:\d\d:\d\d.\d\d\d)/ will work as well, assuming the beginning time is always displayed to the 3rd decimal place.
andre
03-09-2004, 06:35 PM
Fantastic, thank users. I'll be able to put your tips to the test later this week. much thanks!
PS. I have several perl books(oreily) learning perl, cookbook, and for administrators, perhaps I was not looking closely enough, but I don't think that information was in there, is mastering expresions a good book to have?