Не понятная работа регулярки

Статус
В этой теме нельзя размещать новые ответы.

Ragger

Постоялец
Регистрация
14 Июн 2008
Сообщения
166
Реакции
186
Задача найти тег <a и второй в пределах 150 символах.
Соответственно пишу
Код:
<a .*?</a>.{0,150}<a
и выделяется очень много текста
Скрытое содержимое доступно для зарегистрированных пользователей!

если оставить
Код:
<a .*?</a>.{0,150}
то правильно показывает пределы поиска
Скрытое содержимое доступно для зарегистрированных пользователей!

Почему так и как правильно?

Текст для тестов:
Код:
<p><em><strong><a href="http://www.livescience.com/21374-cuttlefish-gender-bending-disguise.html" target="_hplink">By Stephanie Pappas, LiveScience Senior Writer:</a></strong></em></p>

<p>Squid-like cuttlefish are known for their amazing camouflage abilities, thanks to specialized skin cells that allow them to change color in the blink of an eye. Now research finds that these clever mollusks use their color-changing abilities in creative ways: by pretending to be the other gender.</p>

<p>Well, half-pretending, that is.  </p>

<p>When a male cuttlefish is wooing a lady, he often "cheats" by painting typical female patterns on one side of his body, while the other side (the one facing the female)  shows off <a href="http://www.livescience.com/12688-psychedelic-cephalopods-swiftly-switch-color-schemes.html">typical male patterns</a>. This gender-bending disguise fools rival males into thinking they're seeing just a couple of ladies hanging out. That means more of an opportunity for the cheater cuttlefish to mate.</p>

<p>"By using this sneaky display, the males are buying more time to convince the girls to mate before they are discovered by other males," said study researcher Culum Brown, a biologist at Macquarie University in Australia. [<a href="http://www.livescience.com/18482-cuttlefish-camouflage-album.html">Photos: Cute, Color-Changing Cuttlefish</a>]</p>

<p><strong>Clever cuttlefish</strong></p>

<p>Cuttlefish are close relatives of squid and octopuses. Despite their name, they're not fish but mollusks, a group that includes snails and slugs. Still, cuttlefish are quite a bit brighter than your average garden pest. They also have <a href="http://www.livescience.com/18483-cuttlefish-vision-camouflage.html">sophisticated visual systems</a> that allow them to choose the perfect camouflage for any situation.</p>

<p>Brown and his colleagues first noticed the cuttlefish's "two-face" disguise in their laboratory, where they have a semi-natural enclosure for the mollusks. The scientists were conducting a study on anti-predator behavior when a group of <em>Sepia plangon,</em> or mourning cuttlefish, began courting. The researchers noticed that the males sometimes displayed a strange, split-down-the-middle coloration. On the side facing the female, they'd show pulsating stripes. On the side facing a rival male, they'd show mottled camouflage, a typical female look.</p>

<p>The researchers then turned to photographs taken in the Sydney Harbor in Australia, looking for examples of this sneaky behavior in the wild. From other research, they had photographs of 108 cuttlefish groups taken over six years, including 138 individual males.</p>

<p><img alt="dualcolor120703" src="http://i.huffpost.com/gen/674422/thumbs/o-DUALCOLOR120703-570.jpg?1" /><br><em>A male cuttlefish shows his masculine colors to a female while displaying feminine patterns on his opposite side.</em></p>

<p><strong>Putting on a disguise</strong></p>

<p>In 39 percent of the photographed groups containing males, a courting male was sporting gender-bending camouflage. The behavior occurred only in groups where there were two males and one female, the researchers found.</p>

<p>Extra females might have <a href="http://www.livescience.com/13656-noise-pollution-injures-squid-octopus.html">disrupted the male's concentration</a> or simply made it hard for him to orient his disguise in the right direction, they wrote Tuesday (July 3) in the journal Biology Letters.</p>

<p>It might be too risky for the cuttlefish to split his coloring in the presence of more than one rival male, Brown told LiveScience. If another male caught onto the ruse, he'd most likely want to brawl — and fights can ensure that a less-dominant cheating male gets no chance to mate at all. More males hanging around means a greater likelihood of a fight.</p>

<p>For animals that are "<a href="http://www.livescience.com/16475-amazing-mollusks-images-snails.html">effectively snails</a>," cuttlefish are showing off their smarts, Brown said.</p>

<p>"The fact that the males only perform this behavior in a very specific context clearly shows that they are very well aware of the social context in which they find themselves and behave accordingly," he said. Complex social interactions have been put forth to explain why primates and birds show intelligence, he said, and it may be the same for the humble cuttlefish.</p>

<p><em>Follow Stephanie Pappas on Twitter </em><em><a href="http://twitter.com/#!/sipappas">@sipappas</a> </em><em>or LiveScience </em><a href="http://twitter.com/#!/LiveScience"><em>@livescience</em></a><em>. We're also on </em><em><a href="http://www.facebook.com/livescience">Facebook</a> </em><em>& </em><a href="https://plus.google.com/101164570444913213957/posts"><em>Google+</em></a><em>. </em></p>

<p><em>Copyright 2012 <a href="http://LiveScience.com" target="_hplink">LiveScience</a>, a TechMediaNetwork company. All rights reserved. This material may not be published, broadcast, rewritten or redistributed.</em></p>
 
Код:
<a [^>]*?>[^<]*?</a>.{0,150}<a

или даже так:

Код:
</a>.{0,150}<a

Смотря что нужно

А с работой регулярки всё понятно, у вас ведь есть конструкция .*? которая по сути позволяет найти всё, что угодно.
 
Работает спасибо!
А задача находить и вырезать рядом расположенные ссылки из текста.
Всю жизнь думал, что .*? значит "до первого совпадения"
 
Всю жизнь думал, что .*? значит "до первого совпадения"
Оно то до первого совпадения, но если первое попавшееся совпадение не подходит, тогда оно ищет дальше пока не будет найдено подходящее, то, которое не мешает другим условиям регулярки.
 
А как быть если в теге может быть еще тег типа <a href="#">balba<b>bla</b></a>?
Никак, регулярные выражения не дружат с вложенными конструкциями. Потому для полноценного парсинга HTML они не подходят.
 
Статус
В этой теме нельзя размещать новые ответы.
Назад
Сверху