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 MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looking for an efficient way to parse a string 1

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
Suppose I have a string like this:

my $str = "blah, 10 4.2 blah.. a2 ...blah 34xx2 blah.... blah";

I need to extract numbers and any strings that have one or more digit(s) out of $str, i.e. in the example above, I need to extract the following substrings:

10 4.2 a2 34xx2

I know one way to do this --

Code:
my @buf = split(/\s+/, $str);
my @keep;
foreach (@buf) {
  if($_ =~ /\d/) {
    push @keep, $_;
  }
}

But I don't like it. There should be a better way to implement this. Could someone help? Many thanks!!
 
There is nothing wrong with this approach:

Code:
my @buf = split(/\s+/, $str);
my @keep;
foreach (@buf) {
  if($_ =~ /\d/) {
    push @keep, $_;
  }
}

You could use grep to reduce the code and maybe increase efficiency a little:

Code:
@keep = grep{/\d/} split(/\s+/, $str);

The suggestion posted by feherke is also fine.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Thank you Kevin and Feherke.

Now I want a bit more.

Suppose my string is like this:

$str = "blah ... 10 .. a2 ... (blah 4.5 ... blah) blah...";

And I still want to extract all elements that contain number, EXCLUDING everything in between (), i.e. I want to extract 10 & a2, but not 4.5.

I have to use index/substr/loop to do this, which I don't like. Is there a better way to implement?

Thanks again.
 
The my-requirements-keep-changing question. [wink]

Code:
$str = "blah ... 10 .. a2 ... (blah 4.5 ... blah) blah...";
$str =~ s/\([^)]+\)//g;
@keep = grep{/\d/} split(/\s+/,$str);
print "$_\n" for @keep;

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Thank you, Kevin.

I was hoping I could find a way to do it after I got the answers to my originalt question.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top