Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression

Status
Not open for further replies.

Yarka

Technical User
Joined
Jan 14, 2007
Messages
192
Location
ES
Hi,
I've a file as:
123 sc bl 38t4v 30:08 11:87 st ma
121 sc hhh 647g 11:09 88:89 st ks
...
I need to extract the value 30:08, 11:09. For this reason, I do:

my($sc)= "sc" ;
while(<>){
if(/^(\d+)\t$sc.*\t([^\t]+)\st/){
...
}
.....
}

I need that $2 would be 30:08 when read the first line.
What get I wrong?

Thanks.
 
The main problem in your current regex is the greedy matching of ".*". The second thing that I would point out is that you can identify the second matched field by the fact that it's a time. And finally, I'm going to assume that the $sc is meant as a means of filtering line type. This leaves us with:

Code:
my $sc = "sc";
while (<>){
    if (/^(\d+)\t$sc\t.*?\t(\d+:\d+)\t/) { 
     ... 
    }
.....
}

Note that without the line filtering, this could be simplified a lot.

Code:
if (/(\d+).*?(\d+:\d+)/) {

- Miller
 
If ur on a *nix system, you can do

my $dataField = `cat fileName | awk '{print \$5}'`;
 
I would suggest you try split().
It splits whatever string you have (or $_) into an array, and you can give a regexp to specify the separator.

Say something like:
Code:
my ($sc, @splittedLine);
while(<>) {
  @splittedLine = split /\t/;
  # Now @splittedLine contains the line, but as an array
  if( $splittedLine[1] eq 'sc') {
     $sc = $splittedLine[6];
     ...
     ...
  }
}

Or something likewise...
 
If tab \t is a known delimiter for each record, then I would suggest that you do what MacTommy said as well. You didn't specify that was the case originally, but that would be the best method of separating records if it is true.

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top