Regexp: non greedy?

O

Oliver

Dear all

I know, that its probably a little boring for the "pro"s to answer
question about regexp...
....but, bevor I start to cry I'd like to ask for a helping hand.

I have the following regexp:
$message =~ m/(\:59\:(.+)?(\n\:\d\d\:))/s ;

I am expecting it to grab everything whats between :59: and :70: into
$2.
Unfortunately it does it greedy that for some examples it does not
the add the first but the last match of :59: and :70:.

What can I do, that it matches the first occurance between :59: and :
70: ?

Regards,
Oliver

Example Data:

a)

:21: Hello World
:23A: 12344523423
:59: I Am a line
I am another line
me too
I could be another but mustn't
:70: ABRV
:71A: kkk

b)

:21: Hello World
:23A: 12344523423
:59: I Am a line
I am another line with a number
:70: ABRV
:71G: kkk
:70: ABRV2
:71H: lll
:70: ABRV3
 
R

RedGrittyBrick

Oliver said:
I have the following regexp:
$message =~ m/(\:59\:(.+)?(\n\:\d\d\:))/s ;

I am expecting it to grab everything whats between :59: and :70: into
$2.
Unfortunately it does it greedy that for some examples it does not
the add the first but the last match of :59: and :70:.

What can I do, that it matches the first occurance between :59: and :
70: ?

Regards,
Oliver

Example Data:

[snip, see below]

#!/usr/bin/perl
use strict;
use warnings;

my $x=<<END;
:21: Hello World
:23A: 12344523423
:59: I Am a line
I am another line
me too
I could be another but mustn't
:70: ABRV
:71A: kkk
END

my $y=<<END;
:21: Hello World
:23A: 12344523423
:59: I Am a line
I am another line with a number
:70: ABRV
:71G: kkk
:70: ABRV2
:71H: lll
:70: ABRV3
END

for ($x,$y) {
if (/:59:(.+?):70:/s) {
print "\n'$1'\n";
}
}
 
X

xhoster

Oliver said:
Dear all

I know, that its probably a little boring for the "pro"s to answer
question about regexp...
...but, bevor I start to cry I'd like to ask for a helping hand.

I have the following regexp:
$message =~ m/(\:59\:(.+)?(\n\:\d\d\:))/s ;

The ? above is the "1 or 0 quantifier", not the greedy modifier, as it does
not immediately follow another quantifier. It is quantifying the entire
(.+) expression. To get what you want, you need to move ? inside the
parenthesis.

(.+?)

Xho

--
-------------------- http://NewsReader.Com/ --------------------
The costs of publication of this article were defrayed in part by the
payment of page charges. This article must therefore be hereby marked
advertisement in accordance with 18 U.S.C. Section 1734 solely to indicate
this fact.
 

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,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top