извлечение текста между тегами - PullRequest
0 голосов
/ 30 марта 2011

Мне нужно создать регулярное выражение, чтобы получить все содержимое, которое содержится между двумя тегами, которые либо имеют, либо могут содержать несколько строк между этими тегами.Например:

<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
<block color="blue">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...      
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...

Каждый тег блока отмечает начало нового блока, я пробовал следующее регулярное выражение, но я немного растерялся, как указать, что между скобками может быть что угодно, включая нескольколиний, а также как указать, что ему нужно прекратить извлекать вещи, как только он достигнет другого тега, который говорит

<block color="crimson">(\w+)|<block color="green">(\w+)

woops, я забыл добавить, хотя я не заинтересован в блоках, которые выглядят как:

<block color="purple">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...

Ответы [ 4 ]

4 голосов
/ 30 марта 2011

Я бы не советовал вам использовать для этого регулярное выражение. Сначала посмотрите, можете ли вы сделать содержимое допустимым HTML, добавив закрывающие теги. Тогда используйте что-то вроде нокогири, вот учебник:

http://nokogiri.org/tutorials/parsing_an_html_xml_document.html

Даже если вы не можете очистить HTML, я бы попробовал nokogiri, раньше он работал с довольно разбитым HTML.

Удачи!

2 голосов
/ 30 марта 2011

Использование регулярных выражений для анализа HTML вызывает проблемы, за исключением самых тривиальных, контролируемых обстоятельств. Синтаксический анализатор является более надежным и, в конечном счете, обычно намного проще в обслуживании.

HTML-код недействителен, поскольку теги <block> не завершены. Это приводит к неоднозначному синтаксическому анализу с использованием Nokogiri, но мы можем сыграть на нем небольшую хитрость, чтобы исправить ситуацию, и затем иметь возможность правильно ее проанализировать:

html =<<EOT
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
<block color="blue">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...      
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
EOT

require 'nokogiri'
require 'pp'

doc = Nokogiri::HTML(html.gsub('<block', '</block><block'))
pp doc.search('block').map { |n| n.text }

>> ["\n        This is the text I need and\n        it may also  have other \n        tags in it, and all sorts of \n        things...\n",
>>  "\n        This is the text I need and\n        it may also  have other \n        tags in it, and all sorts of \n        things...\n",
>>  "\n        This is the text I need and\n        it may also  have other \n        tags in it, and all sorts of \n        things...      \n",
>>  "\n        This is the text I need and\n        it may also  have other \n        tags in it, and all sorts of \n        things...\n"]

Путем поиска и замены закрывающих </block> можно вставить перед всеми <block> тегами. Это приводит к тому, что первое вхождение ошибочно, но все остальные достаточно близки, чтобы исправление Нокогири HTML было разумным. Вот как выглядит HTML после исправления:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
</block><block color="blue">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
</block><block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...      
</block><block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
</block>
</body></html>

В этот момент Нокогири может разобраться в документе и найти отдельные блоки. Я использую аксессор CSS, поэтому, если вам нужна лучшая детализация, вы можете настроить CSS или переключиться на XPath.

1 голос
/ 30 марта 2011
str = %q(<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
<block color="blue">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...      
<block color="green">
        This is the text I need and
        it may also <p> have other </p>
        tags in it, and all sorts of 
        things...)

ar = str.split(/<block color="\w+">\n/)
ar.shift #(to get rid of the empty element)
0 голосов
/ 30 марта 2011

Возможно, простой способ выполнить эту задачу - читать строку за строкой, проверяя, начинается ли строка с

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...