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

Perl

Avatar of undefined
Last Comment
tel2

8/22/2022 - Mon
Dave Cross

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
Norie

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
trevor1940

ASKER
Thanx Norie you win only because more complete
tel2

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
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck