perl: Extracting text from string

trevor1940
trevor1940 used Ask the Experts™
on
Hi

I have a string of text that should have 1 or more sub string inside brackets whats the best way to extract each wanted sub string, I then need to do stuff with each of these

The code bellow only grabs the first "Wanted"

print "Hello World!\n";

my $text = "Lorem ipsum dolor sit amet,(Wanted 1) consectetur adipiscing elit. (Wanted 2) (Wanted 3) Nunc bibendum ante diam, a imperdiet purus (Wanted 4) faucibus a. Pellentesque ultricies nibh.";

my @WantedText;
if($text =~ m/\((.*?)\)/ )
  {
     push @WantedText, $1;  
  }
  
  foreach my $want (@WantedText){
      
      print $want . "\n";
  }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dave CrossPerl programmer, author and trainer

Commented:
Grab them all in a single go using "/g".

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $text = 'Lorem ipsum dolor sit amet,(Wanted 1) consectetur adipiscing ' .
           'elit. (Wanted 2) (Wanted 3) Nunc bibendum ante diam, a ' .
           'imperdiet purus (Wanted 4) faucibus a. Pellentesque ultricies ' .
           'nibh.';

my @wanted_text = $text =~ /\((.*?)\)/g;

say for @wanted_text;

Open in new window

Analyst Assistant
Commented:
Try adding the g modifier to return all matches.
@list = ($text =~ m/\((.*?)\)/g);

foreach my $want (@list){
    print $want ."\n";    
}

Open in new window

Author

Commented:
Thanx Norie you win only because more complete
Dave's looks more complete to me, Trev.  He's included the shebang line (#!...), some "use" lines, putting the data into a variable.  And he provided it before Norie did.
The section that Norie provided looks more verbose, but what's more complete about it?  What did Dave fail to include which Morie included?  What does Dave's code do which Norie's doesn't?
Norie's doesn't do anything by itself.  Dave's does - it's a complete script.  I'm not saying Norie's is wrong, but I can't see how it's more complete.

Are you aware that you can give credit to more than one answer, Trev?


Here's an even less "complete" version for you, based on Dave's /g trick:
my $text = "Lorem ipsum dolor sit amet,(Wanted 1) consectetur adipiscing elit. (Wanted 2) (Wanted 3) Nunc bibendum ante diam, a imperdiet purus (Wanted 4) faucibus a. Pellentesque ultricies nibh.";

print join("\n", $text =~ /\((.*?)\)/g) . "\n";

Open in new window

The above doesn't store an array of the results, but I'm not sure you need that or whether just printing results will do.
The output is:
Wanted 1
Wanted 2
Wanted 3
Wanted 4

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial