Simple REGEX-Question

R

Reinhard Glauber

ok, I have read the perldoc about regex but I don't understand (maybe because I'm German ;-) )
the thing with the interrogation mark

I search for 'München' in a string and want also the 4 lines before.

I was told to use:

$html =~ /(.*\n)(?:.*\n){4}.*München /;


but why not simple say:

$html =~ /(.*\n){4}.*München /;

thanks
 
X

Xicheng

Reinhard said:
ok, I have read the perldoc about regex but I don't understand (maybe because I'm German ;-) )
the thing with the interrogation mark

I search for 'München' in a string and want also the 4 lines before.

I was told to use:

$html =~ /(.*\n)(?:.*\n){4}.*München /;
this is not true, it returns 6 lines to $&, and the last line is
terminated with 'München '(no newline"\n"). I guess this is not what
you wanted.
but why not simple say:
$html =~ /(.*\n){4}.*München /;
If you need totally 5 lines exactly, and meanwhile print out all the
contents on the 'München ' line, you may try something like:
$html =~ /((?:.*\n){4}.*München.*\n)/ and print $1;
Better use backreference instead of '$&' to print your data.

Xicheng
 
A

Anno Siegel

Xicheng said:
this is not true, it returns 6 lines to $&, and the last line is
terminated with 'München '(no newline"\n"). I guess this is not what
you wanted.

If you need totally 5 lines exactly, and meanwhile print out all the
contents on the 'München ' line, you may try something like:
$html =~ /((?:.*\n){4}.*München.*\n)/ and print $1;
Better use backreference instead of '$&' to print your data.

Terminology alert!

"Backreferences" means to the use of the escapes "\1", \2", etc. inside
a regex to refer back to earlier captures in the current match. The
variables $1, $2, etc. are variously called "capture variables", "digit
variables" or other things, but "backreference" is best reserved for the
escaped form.

Anno
 

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

Similar Threads


Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top