regexp question

  • Thread starter Bart van den Burg
  • Start date
B

Bart van den Burg

Hi

Say i have this code:

perl -we 'my $string = "abc help cba abc help cba"; $string =~
/abc(.*)cba/s; print "$1\n";';

this prints about: " help cba abc help ".
However, i wish for it to only match (the first) " help "...

What do i need to change in order for this to work?

Thanks
Bart
 
A

Arndt Jonasson

Bart van den Burg said:
Say i have this code:

perl -we 'my $string = "abc help cba abc help cba"; $string =~
/abc(.*)cba/s; print "$1\n";';

this prints about: " help cba abc help ".
However, i wish for it to only match (the first) " help "...

What do i need to change in order for this to work?

Use "*?" for matching:

perl -we 'my $string = "abc help cba abc help cba"; $string =~
/abc(.*?)cba/s; print "$1\n";';

See
perldoc -q greedy.
 
D

D. Marxsen

Bart van den Burg said:
perl -we 'my $string = "abc help cba abc help cba"; $string =~
/abc(.*)cba/s; print "$1\n";';

this prints about: " help cba abc help ".
However, i wish for it to only match (the first) " help "...

What do i need to change in order for this to work?

You fell into the "greedy"-trap. Try this:

my $string = "abc help cba abc help cba";
$string =~/abc(.*)cba/s; # Your version
print "$1\n";
$string =~/abc(.*?)cba/s; # Try this
print "$1\n";

Cheers,
Detlef.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,248
Latest member
MagdalenaB

Latest Threads

Top