Link to home
Start Free TrialLog in
Avatar of trevor1940
trevor1940

asked on

perl: Extracting text from string

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

Avatar of Dave Cross
Dave Cross
Flag of United Kingdom of Great Britain and Northern Ireland image

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

ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of trevor1940
trevor1940

ASKER

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