Регулярное выражение выделяет весь текст между тегами

Как лучше всего выбрать выделите весь текст между двумя тегами - например: текст между всеми предварительными тегами на странице.

115
задан user990423 11 November 2015 в 19:00
поделиться

1 ответ

В Python устанавливая эти DOTALL флаг получит все, включая новые строки.

, Если флаг DOTALL был указан, это соответствует любому символу включая новую строку. docs.python.org

#example.py using Python 3.7.4  
import re

str="""Everything is awesome! <pre>Hello,
World!
    </pre>
"""

# Normally (.*) will not capture newlines, but here re.DOTATLL is set 
pattern = re.compile(r"<pre>(.*)</pre>",re.DOTALL)
matches = pattern.search(str)

print(matches.group(1))

python example.py

Hello,
World!

текст Получения между всеми открывающими и закрывающими тэгами в документе

Для получения текста между всеми открывающими и закрывающими тэгами в документе, finditer полезен. В примере ниже, три открытия и закрытие <pre> теги присутствуют в строке.

#example2.py using Python 3.7.4
import re

# str contains three <pre>...</pre> tags
str = """In two different ex-
periments, the authors had subjects chat and solve the <pre>Desert Survival Problem</pre> with a
humorous or non-humorous computer. In both experiments the computer made pre-
programmed comments, but in study 1 subjects were led to believe they were interact-
ing with another person. In the <pre>humor conditions</pre> subjects received a number of funny
comments, for instance: “The mirror is probably too small to be used as a signaling
device to alert rescue teams to your location. Rank it lower. (On the other hand, it
offers <pre>endless opportunity for self-reflection</pre>)”."""

# Normally (.*) will not capture newlines, but here re.DOTATLL is set
# The question mark in (.*?) indicates non greedy matching.
pattern = re.compile(r"<pre>(.*?)</pre>",re.DOTALL)

matches = pattern.finditer(str)


for i,match in enumerate(matches):
    print(f"tag {i}: ",match.group(1))

python example2.py

tag 0:  Desert Survival Problem
tag 1:  humor conditions
tag 2:  endless opportunity for self-reflection
0
ответ дан 24 November 2019 в 02:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: