Re: Capture only first match in regular expression

the default behaviour of regular expression terms is to be "greedy", so to
suppress this behaviour to become "not greedy" you have to apply a single
question mark "?" right after the desired expression(s). Sounds some kind of
complex, but I hope you get me ;-)

In your case the following should be sufficient:

# old: if($content =~ /.*(<a.*<\/a>).*/i){
$anchorContent = $1;

# new:
if($content =~ /.*?(<a.*?<\/a>).*/i){
$anchorContent = $1;

The effect is, that the first expression ".*" becomes not so greedy eating
all the possible chars (incl. one/some "<a" chars that prefix the last
occurrence of "<a" in the current line). Same with the second ".*".

Hope this helps ;-)

Bye.

PiT

"Zapanaz" <http://joecosby.com/code/mail.pl> schrieb im Newsbeitrag
news:...
> Excuse the cross-post, my server doesn't carry comp.lang.perl.misc but
> it looks like there is more activity there.
>
>
> The answer to this is probably staring me in the face ...
>
> I am parsing/page scraping some HTML. I know the first anchor tag <a>
> contains information I want.
>
> So I do this:
>
> if($content =~ /.*(<a.*<\/a>).*/i){
> $anchorContent = $1;
>
> This basically works the way I want, it matches an anchor tag and
> captures the content of it.
>
> But there are multiple anchor tags in the HTML. What I want is the
> first one, but what I get is the last one.
>
> I think I should be using one of these
>
> * Match 0 or more times
> + Match 1 or more times
> ? Match 1 or 0 times
> {n} Match exactly n times
> {n,} Match at least n times
> {n,m} Match at least n but not more than m times
>
> To be honest, I really don't know how (n) is actually supposed to
> look. Would I actually use /a(1)/ to match "a" only one time?
>
>
>
> --
> Zapanaz
> International Satanic Conspiracy
> Customer Support Specialist
> http://joecosby.com/
> Despite the strange appearance of the scooters, the Chinese ant-terror
> police are lethal in action.
>
> :: Currently listening to No 21 in C major K467 Allegro maestoso, 1785, by
> Mozart, from "Piano Concertos - Vladimir Ashkenazy"

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Ask a Question